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

import { ButtonGroupWrapper } from './StyledCheckbox';
import CheckboxButton from './CheckboxButton';

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

export interface CheckboxButtonGroupProps extends CommonProps {
  /**
   * 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;
  }[];
  /**
   * The size of the checkbox.
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Selected value.
   */
  value: (string | number)[];
}

const CheckboxButtonGroup = ({
  name,
  value,
  options,
  onChange,
  size = 'medium',
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: CheckboxButtonGroupProps): ReactElement => (
  <ButtonGroupWrapper
    themeSize={size}
    id={id}
    className={className}
    style={{ ...style, ...css(sx) }}
    data-test-id={dataTestId}
  >
    {options.map(option => (
      <CheckboxButton
        key={option.value}
        text={option.text}
        value={option.value}
        disabled={option.disabled}
        name={name}
        checked={value.includes(option.value)}
        onChange={(e): void => {
          const newValue = e.target.checked
            ? [...value, option.value]
            : value.filter(v => v !== option.value);
          onChange(newValue);
        }}
        size={size}
      />
    ))}
  </ButtonGroupWrapper>
);

export default CheckboxButtonGroup;
