import { BaseSelectProps } from '@mui/material'
import { ReactNode } from 'react'
import { Controller } from 'react-hook-form'
import { SingleSelect } from '../Input'

type Props = {
  name: string
  control: any
  options: Array<{ label: ReactNode; value: any }>
  firstItemEmpty?: boolean
  onOpen?: (e: any) => void
} & BaseSelectProps

export default function FormSingleSelect(props: Props) {
  const {
    name = 'select',
    options = [],
    control,
    label,
    onChange,
    value,
    firstItemEmpty = false,
  } = props

  const inputOptions = firstItemEmpty
    ? [{ label: 'All', value: '__empty__' }, ...options]
    : options

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <SingleSelect
          label={label}
          name={name}
          onChange={onChange ?? field.onChange}
          value={value ?? field?.value}
          options={inputOptions}
          error={!!error}
          onOpen={props?.onOpen}
          helperText={error?.message}
          {...props}
        />
      )}
    />
  )
}
