import { BaseSelectProps } from '@mui/material'
import { useEffect, useState } from 'react'
import axios from '../../config/axios'
import { SingleSelect } from '../Input'

type FeeTypeSelectorProps = {
  name?: string
  label: string
  required?: boolean
  allowAll?: boolean
  onChange?: (value: any) => void
  error?: boolean
  helperText?: string
} & BaseSelectProps
export default function FeeTypeSelector(props: FeeTypeSelectorProps) {
  const { name, required = false, label, onChange, allowAll = true } = props
  const [options, setOptions] = useState([])

  const handleOpen = () => {
    if (options.length === 0) {
      axios
        .get('/paymentx/fee-types', {
          workspace: false,
        })
        .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 (
    <SingleSelect
      name={name}
      label={label}
      required={required}
      options={handleOptions}
      onOpen={handleOpen}
      {...props}
    />
  )
}
