// React Imports
import { use, useEffect, 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'

// Type Imports

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../../../../redux-store'
import { useCustomersMutation } from '../../../../../services/mutations/customers'
import { CustomerRequest } from '../../../../../types/services/customer'
import { resetCustomer } from '../../../../../redux-store/slices/customer'

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

// Vars
const initialData = {
  name: '',
  email: '',
  phone: '',
  address: '',
  is_active: true
}

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

  // Props
  const { open, handleClose } = props

  const { createCustomer, updateCustomer } = useCustomersMutation()
  const { currentCustomer } = useSelector((state: RootState) => state.customerReducer)

  // States
  const [formData, setFormData] = useState<CustomerRequest>(initialData)

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

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

    if (currentCustomer.id) {
      updateCustomer.mutate(
        { id: currentCustomer.id, payload: formData },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    } else {
      createCustomer.mutate(formData, {
        onSuccess: () => {
          handleReset()
        }
      })
    }
  }

  const handleReset = () => {
    handleClose()
    dispatch(resetCustomer())
    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'>{currentCustomer.id ? 'Edit' : 'Add'} Customer</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}
            />
            <CustomTextField
              fullWidth
              type='email'
              label='Email'
              name='email'
              placeholder='johndoe@email'
              value={formData.email}
              onChange={handleInputChange}
            />
            <Typography color='text.primary' className='font-medium'>
              Shipping Information
            </Typography>
            <CustomTextField
              fullWidth
              label='Address Line 1'
              name='address'
              placeholder='45 Roker Terrace'
              value={formData.address}
              onChange={handleInputChange}
            />
            <CustomTextField
              label='Mobile'
              type='number'
              fullWidth
              placeholder='+(123) 456-7890'
              name='phone'
              value={formData.phone}
              onChange={handleInputChange}
            />
            <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' disabled={createCustomer.isPending || updateCustomer.isPending}>
                {currentCustomer.id
                  ? updateCustomer.isPending
                    ? 'Updating...'
                    : 'Update'
                  : createCustomer.isPending
                    ? 'Creating...'
                    : 'Create'}
              </Button>
              <Button variant='tonal' color='error' type='reset' onClick={handleReset}>
                Discard
              </Button>
            </div>
          </form>
        </div>
      </PerfectScrollbar>
    </Drawer>
  )
}

export default AddCustomerDrawer
