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';

import { formatAnswerCheckbox } from 'src/utils/form';

export type MultipleCheckBoxProps = {
  name?: string;
  options?: any[];
  required?: boolean;
  answerInput?: { answer: any[] | null };
  formFilled?: boolean;
};

export const MultipleCheckBox: FC<MultipleCheckBoxProps> = props => {
  const { name, options, required, answerInput, formFilled } = props;

  const { control } = useFormContext();

  const handleChange = (event, value) => {
    if (event.target.checked) {
      return {
        ...value,
        [event.target.name]: formatAnswerCheckbox(event.target.name),
      };
    }
    delete value[event.target.name];
    const checkSelectedItem = Object.keys(value).length > 0;
    return checkSelectedItem ? { ...value } : {};
  };

  const verifyInputChecked = (value, description, id) =>
    !!value && !!value[`${description}-${id}`];

  const defaultValue = answerInput?.answer?.reduce(
    (acc, { id, description, checked }) =>
      checked ? { ...acc, [`${description}-${id}`]: description } : acc,
    {},
  );

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

export default MultipleCheckBox;
