import { BaseSelectProps } from '@mui/material'
import { useEffect, useState } from 'react'
import { Controller } from 'react-hook-form'
import axios from '../../../../config/axios'
import { MultiSelect } from '../../../Input'

type MultiProgramSelectorProps = {
  control: any
  name?: string
  label: string
  required?: boolean
  onChange?: (value: any) => void
  allowAll?: boolean
  error?: boolean
  helperText?: string
} & BaseSelectProps
const MultiFeeTypeSelector = (props: MultiProgramSelectorProps) => {
  const {
    control,
    onChange,
    name,
    required = false,
    label,
    multiple = false,
    value,
    allowAll = true,
  } = props
  const [options, setOptions] = useState([])
  const [prevCourseId, setPrevCourseId] = useState(null)
  const handleOpen = () => {
    if (options.length === 0) {
      axios
        .get('/paymentx/fee-types')
        .then((response) => {
          setOptions(response.data)
        })
        .catch((error) => {
          console.error('Error fetching data from the API:', error)
        })
    }
  }
  useEffect(() => {
    if (props?.value && props.value != 'all') {
      handleOpen()
    }
  }, [props.value])

  const handleOptions =
    options.length > 0
      ? [
          ...(allowAll ? [{ value: 'all', label: 'All' }] : []),
          ...options.map((item) => ({
            label: `${item.name}`,
            value: `${item.id}`,
          })),
        ]
      : allowAll
      ? [{ value: 'all', label: 'All' }]
      : []

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <MultiSelect
          name={name}
          label={label}
          required={required}
          options={handleOptions}
          onOpen={handleOpen}
          onChange={onChange ?? field.onChange}
          value={value ?? field?.value}
          error={!!error}
          helperText={error?.message}
        />
      )}
    />
  )
}
export default MultiFeeTypeSelector
