import { FC } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

import Checkbox from '@material-hu/mui/Checkbox';
import FormControlLabel from '@material-hu/mui/FormControlLabel';
import FormGroup from '@material-hu/mui/FormGroup';

export type ReviewMultipleCheckboxProps = {
  name?: string;
  options?: {
    id: string;
    description: string;
    capability: string;
  }[];
  isRequired?: boolean;
  answer?: number[];
  formFilled?: boolean;
  indexAsValue?: boolean;
};

export const ReviewMultipleCheckbox: FC<
  ReviewMultipleCheckboxProps
> = props => {
  const { name, options, isRequired, answer, formFilled } = props;

  const { control } = useFormContext();

  const handleChange = (event, value, index) => {
    if (event.target.checked) {
      return [...value, index];
    }

    return value.filter(elem => elem !== index);
  };

  const verifyInputChecked = (value, index) => value.includes(index);

  const defaultValue = answer || [];

  return (
    <Controller
      name={name}
      rules={{ required: isRequired && !formFilled }}
      control={control}
      defaultValue={defaultValue}
      render={({ field: { onChange, value } }) => (
        <FormGroup>
          {options.map((capability, index) => (
            <FormControlLabel
              key={`${capability.description}-${capability.id}`}
              disabled={formFilled}
              control={
                <Checkbox
                  name={`${capability.description}-${capability.id}`}
                  checked={verifyInputChecked(
                    formFilled && defaultValue.length ? defaultValue : value,
                    index,
                  )}
                  onChange={e => onChange(handleChange(e, value, index))}
                />
              }
              label={capability.description}
            />
          ))}
        </FormGroup>
      )}
    />
  );
};

export default ReviewMultipleCheckbox;
