// React Imports
import { 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 { MenuItem } from '@mui/material'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../../../../redux-store'
import { usePaymentMethodsMutation } from '../../../../../services/mutations/paymentMethods'
import { PaymentMethodRequest } from '../../../../../types/services/paymentMethod'
import { resetPaymentMethod } from '../../../../../redux-store/slices/paymentMethod'

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

// Vars
const initialData = {
  name: '',
  type: '',
  is_active: true
}

const AddPaymentMethodDrawer = (props: Props) => {
  const dispatch = useDispatch()
  // Props
  const { open, handleClose } = props

  const { createPaymentMethod, updatePaymentMethod } = usePaymentMethodsMutation()
  const { currentPaymentMethod } = useSelector((state: RootState) => state.paymentMethodReducer)

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

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

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

    if (currentPaymentMethod.id) {
      updatePaymentMethod.mutate(
        { id: currentPaymentMethod.id, payload: formData },
        {
          onSuccess: () => {
            handleReset()
          }
        }
      )
    } else {
      createPaymentMethod.mutate(formData, {
        onSuccess: () => {
          handleReset()
        }
      })
    }
  }

  const handleReset = () => {
    handleClose()
    dispatch(resetPaymentMethod())
    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'>{currentPaymentMethod.id ? 'Edit' : 'Add'} Payment Method</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='BCA'
              value={formData.name}
              onChange={handleInputChange}
            />
            <CustomTextField
              select
              fullWidth
              label='Type'
              value={formData.type}
              onChange={e => setFormData({ ...formData, type: e.target.value })}
            >
              <MenuItem value={'cash'}>Cash</MenuItem>
              <MenuItem value={'card'}>Card</MenuItem>
              <MenuItem value={'digital_wallet'}>Digital Wallet</MenuItem>
            </CustomTextField>
            <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={createPaymentMethod.isPending || updatePaymentMethod.isPending}
              >
                {currentPaymentMethod.id
                  ? updatePaymentMethod.isPending
                    ? 'Updating...'
                    : 'Update'
                  : createPaymentMethod.isPending
                    ? 'Creating...'
                    : 'Create'}
              </Button>
              <Button variant='tonal' color='error' type='reset' onClick={handleReset}>
                Discard
              </Button>
            </div>
          </form>
        </div>
      </PerfectScrollbar>
    </Drawer>
  )
}

export default AddPaymentMethodDrawer
