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

import InputSelectableList from '@material-hu/components/composed-components/dynamic-forms/components/FormInputs/InputSelectableList';

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

type Props = {
  name: string;
  choices?: any[];
  required?: boolean;
  formFilled?: boolean;
  multiple: boolean;
  validations?: InputValidations;
};

export const ListChoiceInput = ({
  name,
  choices,
  required,
  formFilled,
  multiple,
  validations,
}: Props) => {
  const { t } = useLokaliseTranslation(['service_management', 'validations']);
  const { control } = useFormContext();

  const { minItems, maxItems } = validations ?? {};

  const validateItems = (value: number[]) => {
    if (!multiple) return true;
    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;
  };

  const parsedChoices = useMemo(() => {
    return (
      choices?.map((choice, idx) => {
        return {
          id: idx,
          value: idx.toString(),
          label: choice as string,
        };
      }) ?? []
    );
  }, [choices]);

  return (
    <Controller
      name={name}
      control={control}
      rules={{
        required: required && !formFilled ? t('validations:required') : false,
        validate: multiple ? validateItems : undefined,
      }}
      render={() => (
        <InputSelectableList
          name={name}
          isMultipleSelect={multiple}
          options={parsedChoices}
          disabled={formFilled}
        />
      )}
    />
  );
};

export default ListChoiceInput;
