// React Imports
import { useEffect, useMemo, useState } from 'react'

// MUI Imports
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Typography from '@mui/material/Typography'

// Third-party Imports

// Type Imports

// Components Imports
import CustomTextField from '@core/components/mui/TextField'
import { Autocomplete, CircularProgress } from '@mui/material'
import { useDebounce } from 'use-debounce'
import { useUnitsMutation } from '../../../../../services/mutations/units'
import { useOutlets } from '../../../../../services/queries/outlets'
import { Unit, UnitRequest } from '../../../../../types/services/unit'

type Props = {
  open: boolean
  handleClose: () => void
  data: Unit
}

const EditUnitDrawer = (props: Props) => {
  // Props
  const { open, handleClose, data } = props

  // States
  const [formData, setFormData] = useState<UnitRequest>({
    name: '',
    abbreviation: '',
    outlet_id: '',
    is_active: true
  })
  const [status, setStatus] = useState('')
  const [outletInput, setOutletInput] = useState('')
  const [outletDebouncedInput] = useDebounce(outletInput, 500)

  const { data: outlets, isLoading: outletsLoading } = useOutlets({
    search: outletDebouncedInput
  })

  const { mutate: updateUnit, isPending: isCreating } = useUnitsMutation().updateUnit
  const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])

  useEffect(() => {
    if (data) {
      setFormData({
        name: data.name,
        abbreviation: data.abbreviation!,
        outlet_id: data.outlet_id!,
        is_active: data.is_active
      })
      setStatus(data.is_active ? 'active' : 'inactive')
    }
  }, [data])

  // Handle Form Submit
  const handleFormSubmit = (e: any) => {
    e.preventDefault()

    updateUnit(
      { id: data.id, payload: formData },
      {
        onSuccess: () => {
          handleReset()
        }
      }
    )
  }

  const handleInputChange = (e: any) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    })
  }

  // Handle Form Reset
  const handleReset = () => {
    handleClose()
    setFormData({
      name: '',
      abbreviation: '',
      outlet_id: '',
      is_active: true
    })
  }

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 400 } } }}
    >
      <div className='flex items-center justify-between pli-6 plb-5'>
        <Typography variant='h5'>Edit Unit</Typography>
        <IconButton size='small' onClick={handleReset}>
          <i className='tabler-x text-textSecondary text-2xl' />
        </IconButton>
      </div>
      <Divider />
      <div className='p-6'>
        <form onSubmit={handleFormSubmit} className='flex flex-col gap-5'>
          <CustomTextField
            fullWidth
            label='Name'
            name='name'
            value={formData.name || ''}
            onChange={handleInputChange}
            placeholder='pcs'
          />
          <CustomTextField
            fullWidth
            label='Abbreviation'
            name='abbreviation'
            value={formData.abbreviation || ''}
            onChange={handleInputChange}
            placeholder='enter abbreviation'
          />
          <Autocomplete
            options={outletOptions}
            loading={outletsLoading}
            getOptionLabel={option => option.name}
            value={outletOptions.find(p => p.id === formData.outlet_id) || null}
            onInputChange={(event, newOutlettInput) => {
              setOutletInput(newOutlettInput)
            }}
            onChange={(event, newValue) => {
              setFormData({
                ...formData,
                outlet_id: newValue?.id || ''
              })
            }}
            renderInput={params => (
              <CustomTextField
                {...params}
                className=''
                label='Outlet'
                fullWidth
                InputProps={{
                  ...params.InputProps,
                  endAdornment: (
                    <>
                      {outletsLoading && <CircularProgress size={18} />}
                      {params.InputProps.endAdornment}
                    </>
                  )
                }}
              />
            )}
          />
          <CustomTextField select fullWidth label='Status' value={status} onChange={e => setStatus(e.target.value)}>
            <MenuItem value={'active'}>Active</MenuItem>
            <MenuItem value={'inactive'}>Inactive</MenuItem>
          </CustomTextField>
          <div className='flex items-center gap-4'>
            <Button variant='contained' type='submit' disabled={isCreating}>
              {isCreating ? 'Updating...' : 'Update'}
            </Button>
            <Button variant='tonal' color='error' type='reset' onClick={handleReset}>
              Discard
            </Button>
          </div>
        </form>
      </div>
    </Drawer>
  )
}

export default EditUnitDrawer
