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

type CourseSelectorProps = {
  name?: string
  label: string
  required?: boolean
  onChange?: (value: any) => void
  allowAll?: boolean
  error?: boolean
  helperText?: string
  api?: string
  valueByUniqueId?: boolean
} & BaseSelectProps
export default function CourseSelector(props: CourseSelectorProps) {
  const {
    name,
    required = false,
    label,
    onChange,
    allowAll = true,
    valueByUniqueId = false,
    api = '/paymentx/domain/courses',
  } = props
  const [options, setOptions] = useState([])

  const handleOpen = () => {
    if (options.length === 0) {
      axios
        .get(api)
        .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.courseName} `,
            value: !valueByUniqueId ? `${item.id}` : `${item.uniqueId}`,
          })),
        ]
      : allowAll
      ? [{ value: 'all', label: 'All' }]
      : []

  return (
    <SingleSelect
      name={name}
      label={label}
      required={required}
      options={handleOptions}
      onOpen={handleOpen}
      {...props}
    />
  )
}
