import { Box, BoxProps, FormGroup, FormHelperText } from '@mui/material'
import { ReactNode } from 'react'
import FormLabel from './FormLabel'
import SingleCheckbox from './SingleCheckbox'

interface Props {
  label?: ReactNode
  name: string
  size?: 'small' | 'medium'
  options: Array<{ label: ReactNode; value: any; disabled?: boolean }>
  required?: boolean
  disabled?: boolean
  row?: boolean
  error?: boolean
  helperText?: ReactNode
  value: { label: string; value: any }[]
  onChange: (value: { label: ReactNode; value: any }[]) => void
  containerProps?: BoxProps
}

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