import { AutocompleteInputChangeReason } from '@mui/material'
import { ReactNode } from 'react'
import { Controller } from 'react-hook-form'
import { MultiSelect } from '../Input'
import { IOption } from '../Input/types'

interface MultiSelectProps {
  control: any
  label: ReactNode
  size?: string
  name: string
  options: IOption[]
  placeholder?: string
  loading?: boolean
  onInputChange?: (
    event: React.SyntheticEvent,
    value: string,
    reason: AutocompleteInputChangeReason,
  ) => void
  required?: boolean
  disabled?: boolean
  value?: IOption[] | IOption
  onChange?: (value: IOption[] | IOption) => void
  multiple?: boolean
  noOptionsText?: string
  limitTags?: number
}

export default function FormMultiSelect({
  control,
  name,
  options,
  label,
  loading,
  required,
  disabled = false,
  multiple = true,
  noOptionsText,
  onInputChange,
  limitTags = -1,
  ...props
}: MultiSelectProps) {
  return (
    <Controller
      control={control}
      name={name}
      render={({ field, fieldState: { error } }) => {
        return (
          <MultiSelect
            multiple={multiple}
            value={field.value}
            label={label}
            onChange={(value) => {
              field.onChange(value)
            }}
            onInputChange={onInputChange}
            loading={loading}
            options={options || []}
            error={!!error}
            noOptionsText={noOptionsText}
            required={required}
            disabled={disabled}
            helperText={error ? error.message : null}
            limitTags={limitTags}
            {...props}
          />
        )
      }}
    />
  )
}
