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

type ExamGroupSelectorProps = {
  name?: string
  label: string
  filters?: { courseId: number; examType: string }
  required?: boolean
  onChange?: (value: any) => void
  allowAll?: boolean
  error?: boolean
  helperText?: string
} & BaseSelectProps
const ExamGroupSelector = (props: ExamGroupSelectorProps) => {
  const {
    name,
    required = false,
    label,
    multiple = false,
    filters,
    allowAll = true,
  } = props
  const [options, setOptions] = useState([])
  const [prevExamType, setPrevExamType] = useState(null)
  const [prevCourseId, setPrevCourseId] = useState(null)
  let api =
    filters?.examType !== 'internal'
      ? '/exams/exams/exam-groups'
      : '/exams/internal-exams'
  const handleOpen = () => {
    if (filters) {
      if (
        (filters?.examType && filters?.examType !== prevExamType) ||
        (filters?.courseId && filters?.courseId !== prevCourseId)
      ) {
        setOptions([])
        axios
          .get(api, {
            params: {
              ...filters,
              isArchived: 'false',
              isExamPublished: 'true',
            },
            workspace: false,
          })
          .then((response) => {
            setOptions(
              filters?.examType !== 'internal'
                ? response.data?.examGroups
                : response.data?.exams,
            )
            setPrevExamType(filters?.examType)
            setPrevCourseId(filters?.courseId)
          })
          .catch((error) => {
            console.error('Error fetching data from the API:', error)
          })
      }
    } else if (options.length === 0) {
      axios
        .get(api, {
          params: {
            isArchived: 'false',
            isExamPublished: 'true',
          },
          workspace: false,
        })
        .then((response) => {
          setOptions(
            filters?.examType !== 'internal'
              ? response.data?.examGroups
              : response.data?.exams,
          )
        })
        .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:
              filters?.examType != 'internal'
                ? item?.groupName
                : item?.displayName,
            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 ExamGroupSelector
