import React, { ReactElement } from 'react';
import css from '../../utils/css';

import { GroupWrapper } from './StyledCheckbox';
import Checkbox from './Checkbox';

import { CommonProps } from '../common';

export interface CheckboxGroupProps extends CommonProps {
  /**
   * Layout to render checkboxes.
   */
  layout?: 'vertical' | 'horizontal';
  /**
   * Checkbox group name, used for form submission.
   */
  name?: string;
  /**
   * Change event handler.
   */
  onChange: (value: (string | number)[]) => void;
  /**
   * An array of checkbox options to be selected.
   */
  options: {
    disabled?: boolean;
    text: string;
    value: string | number;
  }[];
  /**
   * Selected value.
   */
  value: (string | number)[];
}

const CheckboxGroup = ({
  name,
  value,
  options,
  onChange,
  layout = 'vertical',
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: CheckboxGroupProps): ReactElement => {
  return (
    <GroupWrapper
      themeLayout={layout}
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      {options.map(option => (
        <Checkbox
          key={option.value}
          value={option.value}
          text={option.text}
          name={name}
          checked={value.includes(option.value)}
          disabled={option.disabled}
          onChange={(e): void => {
            const newValue = e.target.checked
              ? [...value, option.value]
              : value.filter(v => v !== option.value);
            onChange(newValue);
          }}
        />
      ))}
    </GroupWrapper>
  );
};

export default CheckboxGroup;
