// 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 Switch from '@mui/material/Switch'
import Typography from '@mui/material/Typography'

// Third-party Imports
import PerfectScrollbar from 'react-perfect-scrollbar'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../../../../redux-store'
import { useIngredientsMutation } from '../../../../../services/mutations/ingredients'
import { IngredientRequest } from '../../../../../types/services/ingredient'
import { Autocomplete, CircularProgress } from '@mui/material'
import { useOutlets } from '../../../../../services/queries/outlets'
import { useDebounce } from 'use-debounce'
import { useUnits } from '../../../../../services/queries/units'
import { resetIngredient } from '../../../../../redux-store/slices/ingredient'

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

// Vars
const initialData = {
  name: '',
  unit_id: '',
  cost: 0,
  stock: 0,
  is_semi_finished: false,
  outlet_id: ''
}

const AddProductIngredientDrawer = (props: Props) => {
  const dispatch = useDispatch()

  // Props
  const { open, handleClose } = props

  const { createIngredient, updateIngredient } = useIngredientsMutation()
  const { currentIngredient } = useSelector((state: RootState) => state.ingredientReducer)

  // States
  const [formData, setFormData] = useState<IngredientRequest>(initialData)
  const [outletInput, setOutletInput] = useState('')
  const [outletDebouncedInput] = useDebounce(outletInput, 500)
  const [unitInput, setUnitInput] = useState('')
  const [unitDebouncedInput] = useDebounce(unitInput, 500)

  const { data: outlets, isLoading: outletsLoading } = useOutlets({
    search: outletDebouncedInput
  })
  const { data: units, isLoading: unitsLoading } = useUnits({
    search: unitDebouncedInput
  })

  const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])
  const unitOptions = useMemo(() => units?.data || [], [units])

  useEffect(() => {
    if (currentIngredient.id) {
      setFormData(currentIngredient)
    }
  }, [currentIngredient])

  const handleSubmit = (e: any) => {
    e.preventDefault()

    const { stock, cost, ...rest } = formData

    const payload = {
      ...rest,
      stock: Number(stock),
      cost: Number(cost)
    }

    if (currentIngredient.id) {
      updateIngredient.mutate(
        { id: currentIngredient.id, payload },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    } else {
      createIngredient.mutate(payload, {
        onSuccess: () => {
          handleReset()
        }
      })
    }
  }

  const handleReset = () => {
    handleClose()
    dispatch(resetIngredient())
    setFormData(initialData)
  }

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

  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'>{currentIngredient.id ? 'Edit' : 'Add'} Ingredient</Typography>
        <IconButton size='small' onClick={handleReset}>
          <i className='tabler-x text-2xl' />
        </IconButton>
      </div>
      <Divider />
      <PerfectScrollbar options={{ wheelPropagation: false, suppressScrollX: true }}>
        <div className='p-6'>
          <form onSubmit={handleSubmit} className='flex flex-col gap-5'>
            <Typography color='text.primary' className='font-medium'>
              Basic Information
            </Typography>
            <CustomTextField
              fullWidth
              label='Name'
              name='name'
              placeholder='John Doe'
              value={formData.name}
              onChange={handleInputChange}
            />
            <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}
                      </>
                    )
                  }}
                />
              )}
            />
            <Autocomplete
              options={unitOptions}
              loading={unitsLoading}
              getOptionLabel={option => option.name}
              value={unitOptions.find(p => p.id === formData.unit_id) || null}
              onInputChange={(event, newUnitInput) => {
                setUnitInput(newUnitInput)
              }}
              onChange={(event, newValue) => {
                setFormData({
                  ...formData,
                  unit_id: newValue?.id || ''
                })
              }}
              renderInput={params => (
                <CustomTextField
                  {...params}
                  className=''
                  label='Unit'
                  fullWidth
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {unitsLoading && <CircularProgress size={18} />}
                        {params.InputProps.endAdornment}
                      </>
                    )
                  }}
                />
              )}
            />
            <CustomTextField
              fullWidth
              type='number'
              label='Cost'
              name='cost'
              placeholder='$499'
              value={formData.cost}
              onChange={handleInputChange}
            />
            <CustomTextField
              label='Stock'
              type='number'
              fullWidth
              placeholder='100'
              name='stock'
              value={formData.stock}
              onChange={handleInputChange}
            />
            <div className='flex items-center'>
              <div className='flex flex-col items-start gap-1'>
                <Typography color='text.primary' className='font-medium'>
                  Semi Finished
                </Typography>
              </div>
              <Switch
                checked={formData.is_semi_finished}
                name='is_semi_finished'
                onChange={e => setFormData({ ...formData, is_semi_finished: e.target.checked })}
              />
            </div>
            <div className='flex items-center gap-4'>
              <Button
                variant='contained'
                type='submit'
                disabled={createIngredient.isPending || updateIngredient.isPending}
              >
                {currentIngredient.id
                  ? updateIngredient.isPending
                    ? 'Updating...'
                    : 'Update'
                  : createIngredient.isPending
                    ? 'Creating...'
                    : 'Create'}
              </Button>
              <Button variant='tonal' color='error' type='reset' onClick={handleReset}>
                Discard
              </Button>
            </div>
          </form>
        </div>
      </PerfectScrollbar>
    </Drawer>
  )
}

export default AddProductIngredientDrawer
