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

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

  const handleOpen = () => {
    if (options.length === 0) {
      axios
        .get(api, {
          workspace: false,
        })
        .then((response) => {
          setOptions(response.data.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}
    />
  )
}
