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

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

import { InputValidations } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type CheckboxInputProps = {
  name: string;
  choices?: any[];
  required?: boolean;
  validations?: InputValidations;
  title?: string;
};

export const CheckboxInput: FC<CheckboxInputProps> = ({
  name,
  choices,
  required,
  validations = {},
  title,
}) => {
  const { t } = useLokaliseTranslation('service_management');

  const { minItems, maxItems } = validations;

  const { control } = useFormContext();

  const validateItems = (value: number[]) => {
    if (minItems && (!value || (value && value.length < minItems))) {
      return t('CHECKBOX_MIN_VALIDATION', { min: minItems });
    }
    if (maxItems && value && value.length > maxItems) {
      return t('CHECKBOX_MAX_VALIDATION', { max: maxItems });
    }
    return true;
  };

  return (
    <Controller
      name={name}
      rules={{
        required: required,
        validate: validateItems,
      }}
      control={control}
      render={({ field: { onChange, value = [] }, fieldState: { error } }) => (
        <FormControl error={!!error}>
          <FormLabel>{title}</FormLabel>
          <FormGroup>
            {choices?.map((choice, index) => (
              <FormControlLabel
                key={index}
                control={
                  <Checkbox
                    checked={value.includes(index)}
                    onChange={event => {
                      const newValue = event.target.checked
                        ? [...value, index]
                        : value.filter((item: number) => item !== index);
                      onChange(newValue);
                    }}
                    name={`${name}[${index}]`}
                    disabled={
                      !value.includes(index) &&
                      value.length >= (maxItems || choices?.length || 0)
                    }
                  />
                }
                label={choice}
              />
            ))}
          </FormGroup>
        </FormControl>
      )}
    />
  );
};

export default CheckboxInput;
