import { Button, Stack } from '@mui/material'
import { useEffect } from 'react'
import { useQuery } from 'react-query'
import { useImmer } from 'use-immer'
import axios from '../../config/axios'
import { SingleSelect } from '../Input'
import Spinner from '../Spinner'

const defaultState = {
  departmentId: '',
}

const getDepartments = () => {
  return axios.get('/hrms/departments').then((res) => res.data?.data)
}

export default function DepartmentFilter({
  close,
  appliedFilters,
  setAppliedFilters,
}) {
  const [filter, setFilter] = useImmer(defaultState)

  const { data, isLoading } = useQuery('department', () => getDepartments())

  useEffect(() => {
    setFilter({ departmentId: appliedFilters.filters.departmentId })
  }, [])

  const applyFilter = () => {
    close()
    setAppliedFilters((s) => {
      s.filters.departmentId = filter.departmentId
      s.filtersApplied = filter.departmentId ? true : false
    })
  }
  const clearFilter = () => {
    setAppliedFilters((s) => {
      s.filters.departmentId = ''
      s.filtersApplied = false
    })
    close()
  }

  if (isLoading) return <Spinner />
  return (
    <>
      <Stack gap={3}>
        <SingleSelect
          label="Select Department"
          onChange={(e) => {
            setFilter((s) => {
              s.departmentId = e.target.value
            })
          }}
          value={filter.departmentId}
          options={
            data &&
            data?.map((item) => ({
              label: item?.name,
              value: item?._id,
            }))
          }
        />

        <Stack direction="row" gap={2} mt={0.5}>
          <Button fullWidth onClick={applyFilter}>
            Apply Filters
          </Button>
          <Button variant="outlined" fullWidth onClick={clearFilter}>
            Clear Filters
          </Button>
        </Stack>
      </Stack>
    </>
  )
}
