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

type ClassRoomSelectorProps = {
  name?: string
  label: string
  filters?: { programId: number; courseId: number; batch: string }
  required?: boolean
  onChange?: (value: any) => void
  allowAll?: boolean
  error?: boolean
  helperText?: string
  api?: string
} & BaseSelectProps
const ClassRoomSelector = (props: ClassRoomSelectorProps) => {
  const {
    name,
    required = false,
    label,
    multiple = false,
    filters,
    allowAll = true,
    api = '/square/classrooms/filters',
  } = props
  const [options, setOptions] = useState([])
  const [prevProgramId, setPrevProgramId] = useState(null)
  const [prevBatch, setPrevBatch] = useState(null)
  const [prevCourseId, setPrevCourseId] = useState(null)
  const handleOpen = () => {
    if (filters) {
      if (
        (filters?.programId && filters?.programId !== prevProgramId) ||
        (filters?.batch &&
          filters?.batch !== prevBatch &&
          filters?.programId) ||
        (filters?.courseId && filters?.courseId !== prevCourseId)
      ) {
        setOptions([])
        axios
          .get(api, {
            params: filters,
          })
          .then((response) => {
            setOptions(response.data)
            setPrevProgramId(filters.programId)
            setPrevBatch(filters.batch)
            setPrevCourseId(filters.courseId)
          })
          .catch((error) => {
            console.error('Error fetching data from the API:', error)
          })
      }
    } else 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.name}`,
            value: `${item.id}`,
          })),
        ]
      : allowAll
      ? [{ value: 'all', label: 'All' }]
      : []

  return (
    <SingleSelect
      name={name}
      label={label}
      required={required}
      options={handleOptions}
      onOpen={handleOpen}
      defaultValue="all"
      {...props}
    />
  )
}
export default ClassRoomSelector
