// 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

// Types Imports

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Autocomplete, Checkbox, FormControl, FormControlLabel, FormGroup, FormLabel, Switch } from '@mui/material'
import { useDispatch, useSelector } from 'react-redux'
import { useDebounce } from 'use-debounce'
import { RootState } from '../../../../redux-store'
import { resetUser } from '../../../../redux-store/slices/user'
import { useUsersMutation } from '../../../../services/mutations/users'
import { useOutlets } from '../../../../services/queries/outlets'
import { UserRequest } from '../../../../types/services/user'

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

// Vars
const initialData = {
  name: '',
  email: '',
  password: '',
  role: '',
  permissions: {
    can_create_orders: false,
    can_void_orders: false
  },
  is_active: true,
  outlet_id: ''
}

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

  // Props
  const { open, handleClose } = props

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

  const { currentUser } = useSelector((state: RootState) => state.userReducer)

  const { createUser, updateUser } = useUsersMutation()

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

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

  useEffect(() => {
    if (currentUser.id) {
      setFormData({
        name: currentUser.name,
        email: currentUser.email,
        role: currentUser.role,
        password: '',
        is_active: currentUser.is_active,
        outlet_id: currentUser.outlet_id,
        permissions: currentUser.permissions
      })
    }
  }, [currentUser])

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

    if (currentUser.id) {
      updateUser.mutate(
        { id: currentUser.id, payload: formData },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    } else {
      createUser.mutate(formData, {
        onSuccess: () => {
          handleReset()
        }
      })
    }
  }

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

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

  const handleCheckBoxChange = (e: any) => {
    const { name, checked } = e.target
    setFormData(prev => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [name]: checked
      }
    }))
  }

  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 plb-5 pli-6'>
        <Typography variant='h5'>{currentUser.id ? 'Edit' : 'Add'} User</Typography>
        <IconButton size='small' onClick={handleReset}>
          <i className='tabler-x text-2xl text-textPrimary' />
        </IconButton>
      </div>
      <Divider />
      <div>
        <form onSubmit={handleSubmit} className='flex flex-col gap-6 p-6'>
          <CustomTextField
            fullWidth
            label='Name'
            placeholder='John Doe'
            name='name'
            value={formData.name}
            onChange={handleInputChange}
          />
          <CustomTextField
            fullWidth
            type='email'
            label='Email'
            placeholder='johndoe@email'
            name='email'
            value={formData.email}
            onChange={handleInputChange}
          />
          {currentUser.id ? null : (
            <CustomTextField
              fullWidth
              type='password'
              label='Password'
              placeholder='********'
              name='password'
              value={formData.password}
              onChange={handleInputChange}
            />
          )}
          <CustomTextField
            select
            fullWidth
            label='Role'
            placeholder='Select Role'
            value={formData.role}
            onChange={e => setFormData({ ...formData, role: e.target.value })}
          >
            <MenuItem value={`manager`}>Manager</MenuItem>
            <MenuItem value={`cashier`}>Cashier</MenuItem>
            <MenuItem value={`waiter`}>Waiter</MenuItem>
          </CustomTextField>
          <Autocomplete
            options={outletOptions}
            loading={outletsLoading}
            getOptionLabel={option => option.name}
            value={outletOptions.find((p: any) => 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: <>{params.InputProps.endAdornment}</>
                }}
              />
            )}
          />
          <FormControl component='fieldset' variant='outlined'>
            <FormLabel component='legend'>Assign permissions</FormLabel>
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={formData.permissions.can_create_orders}
                    onChange={handleCheckBoxChange}
                    name='can_create_orders'
                  />
                }
                label='Can create orders'
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={formData.permissions.can_void_orders}
                    onChange={handleCheckBoxChange}
                    name='can_void_orders'
                  />
                }
                label='Can void orders'
              />
            </FormGroup>
          </FormControl>
          <div className='flex items-center'>
            <div className='flex flex-col items-start gap-1'>
              <Typography color='text.primary' className='font-medium'>
                Active
              </Typography>
            </div>
            <Switch
              checked={formData.is_active}
              name='is_active'
              onChange={e => setFormData({ ...formData, is_active: e.target.checked })}
            />
          </div>
          <div className='flex items-center gap-4'>
            <Button variant='contained' type='submit'>
              {createUser.isPending || updateUser.isPending ? 'Saving...' : 'Save'}
            </Button>
            <Button variant='tonal' color='error' type='reset' onClick={() => handleReset()}>
              Cancel
            </Button>
          </div>
        </form>
      </div>
    </Drawer>
  )
}

export default AddUserDrawer
