import {
  Box,
  BoxProps,
  FormGroup,
  FormGroupProps,
  FormHelperText,
} from '@mui/material'
import { ReactNode } from 'react'
import { Controller } from 'react-hook-form'
import { FormLabel, SingleCheckbox } from '../Input'

interface Props extends FormGroupProps {
  label?: ReactNode
  name: string
  control: any
  options: { label: ReactNode; value: any; disabled?: boolean }[]
  required?: boolean
  disabled?: boolean
  row?: boolean
  containerProps?: BoxProps
  disableSelected?: boolean
}

export default function FormMultiCheckbox({
  name,
  control,
  label = '',
  options = [],
  required = false,
  row = true,
  disableSelected = false,
  disabled = false,
  containerProps,
  ...rest
}: Props) {
  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <Box width="100%" {...containerProps}>
          <FormLabel label={label} name={name} required={required} />
          <FormGroup row={row} sx={{ flexWrap: 'wrap' }} {...rest}>
            {options?.map((item, index) => (
              <SingleCheckbox
                key={index}
                name={name}
                disabled={
                  (disableSelected &&
                    field?.value
                      ?.map((item: any) => item?.value)
                      ?.includes(item?.value)) ||
                  disabled ||
                  item?.disabled
                }
                checked={field?.value
                  ?.map((item: any) => item?.value)
                  ?.includes(item?.value)}
                label={item.label}
                onChange={(e) => {
                  let value = field.value || []
                  if (e.target.checked) {
                    let newValue = [...value, item]
                    field.onChange(newValue)
                  } else {
                    let filteredValue = value.filter(
                      (opt: any) => opt?.value !== item.value,
                    )
                    field.onChange(filteredValue)
                  }
                }}
              />
            ))}
          </FormGroup>
          {error && <FormHelperText>{error.message}</FormHelperText>}
        </Box>
      )}
    />
  )
}
