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

// MUI Imports
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'

// Third-party Imports
import { useForm, Controller } from 'react-hook-form'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Vendor, VendorRequest } from '@/types/services/vendor'
import { useVendorsMutation } from '@/services/mutations/vendor'

type Props = {
  open: boolean
  handleClose: () => void
  data?: Vendor // Data vendor untuk edit (jika ada)
}

type FormValidateType = {
  name: string
  email: string
  phone_number: string
  address: string
  contact_person: string
  tax_number: string
  payment_terms: string
  notes: string
  is_active: boolean
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  email: '',
  phone_number: '',
  address: '',
  contact_person: '',
  tax_number: '',
  payment_terms: '',
  notes: '',
  is_active: true
}

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

  // States
  const [showMore, setShowMore] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const { createVendor, updateVendor } = useVendorsMutation()

  // Determine if this is edit mode
  const isEditMode = Boolean(data?.id)

  // Hooks
  const {
    control,
    reset: resetForm,
    handleSubmit,
    formState: { errors }
  } = useForm<FormValidateType>({
    defaultValues: initialData
  })

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        email: data.email || '',
        phone_number: data.phone_number || '',
        address: data.address || '',
        contact_person: data.contact_person || '',
        tax_number: data.tax_number || '',
        payment_terms: data.payment_terms || '',
        notes: data.notes || '',
        is_active: data.is_active ?? true
      }

      resetForm(formData)

      // Show more fields if any optional field has data
      const hasOptionalData = data.address || data.tax_number || data.payment_terms || data.notes
      if (hasOptionalData) {
        setShowMore(true)
      }
    } else {
      // Reset to initial data for add mode
      resetForm(initialData)
      setShowMore(false)
    }
  }, [data, isEditMode, resetForm])

  const handleFormSubmit = async (formData: FormValidateType) => {
    try {
      setIsSubmitting(true)

      // Create VendorRequest object
      const vendorRequest: VendorRequest = {
        name: formData.name,
        email: formData.email || undefined,
        phone_number: formData.phone_number || undefined,
        address: formData.address || undefined,
        contact_person: formData.contact_person || undefined,
        tax_number: formData.tax_number || undefined,
        payment_terms: formData.payment_terms || undefined,
        notes: formData.notes || undefined,
        is_active: formData.is_active
      }

      if (isEditMode && data?.id) {
        // Update existing vendor
        updateVendor.mutate(
          { id: data.id, payload: vendorRequest },
          {
            onSuccess: () => {
              handleReset()
              handleClose()
            }
          }
        )
      } else {
        // Create new vendor
        createVendor.mutate(vendorRequest, {
          onSuccess: () => {
            handleReset()
            handleClose()
          }
        })
      }
    } catch (error) {
      console.error('Error submitting vendor:', error)
      // Handle error (show toast, etc.)
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleReset = () => {
    handleClose()
    resetForm(initialData)
    setShowMore(false)
  }

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{
        '& .MuiDrawer-paper': {
          width: { xs: 300, sm: 400 },
          display: 'flex',
          flexDirection: 'column',
          height: '100%'
        }
      }}
    >
      {/* Sticky Header */}
      <Box
        sx={{
          position: 'sticky',
          top: 0,
          zIndex: 10,
          backgroundColor: 'background.paper',
          borderBottom: 1,
          borderColor: 'divider'
        }}
      >
        <div className='flex items-center justify-between plb-5 pli-6'>
          <Typography variant='h5'>{isEditMode ? 'Edit Vendor' : 'Tambah Vendor Baru'}</Typography>
          <IconButton size='small' onClick={handleReset}>
            <i className='tabler-x text-2xl text-textPrimary' />
          </IconButton>
        </div>
      </Box>

      {/* Scrollable Content */}
      <Box sx={{ flex: 1, overflowY: 'auto' }}>
        <form id='vendor-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Nama Vendor */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama Vendor <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='name'
                control={control}
                rules={{ required: 'Nama vendor wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Masukkan nama vendor'
                    error={!!errors.name}
                    helperText={errors.name?.message}
                  />
                )}
              />
            </div>

            {/* Email */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Email <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='email'
                control={control}
                rules={{
                  required: 'Email wajib diisi',
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: 'Format email tidak valid'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='email'
                    placeholder='vendor@example.com'
                    error={!!errors.email}
                    helperText={errors.email?.message}
                  />
                )}
              />
            </div>

            {/* Nomor Telepon */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nomor Telepon <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='phone_number'
                control={control}
                rules={{ required: 'Telepon wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField {...field} fullWidth placeholder='Harus Diawali 62' error={!!errors.phone_number} />
                )}
              />
            </div>

            {/* Contact Person */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Contact Person <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='contact_person'
                control={control}
                rules={{ required: 'Contact Person wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Nama contact person'
                    error={!!errors.contact_person}
                  />
                )}
              />
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='is_active'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Vendor Aktif'
                  />
                )}
              />
            </div>

            {/* Tampilkan selengkapnya */}
            {!showMore && (
              <Button
                variant='text'
                color='primary'
                size='small'
                sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
                onClick={() => setShowMore(true)}
              >
                + Tampilkan selengkapnya
              </Button>
            )}

            {/* Konten tambahan */}
            {showMore && (
              <>
                {/* Alamat */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Alamat
                  </Typography>
                  <Controller
                    name='address'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField {...field} fullWidth placeholder='Alamat lengkap vendor' multiline rows={3} />
                    )}
                  />
                </div>

                {/* NPWP/Tax Number */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    NPWP
                  </Typography>
                  <Controller
                    name='tax_number'
                    control={control}
                    render={({ field }) => <CustomTextField {...field} fullWidth placeholder='Nomor NPWP' />}
                  />
                </div>

                {/* Payment Terms */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Syarat Pembayaran
                  </Typography>
                  <Controller
                    name='payment_terms'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField {...field} select fullWidth placeholder='Pilih syarat pembayaran'>
                        <MenuItem value=''>Pilih Syarat Pembayaran</MenuItem>
                        <MenuItem value='CASH'>Cash</MenuItem>
                        <MenuItem value='NET_7'>Net 7 Hari</MenuItem>
                        <MenuItem value='NET_14'>Net 14 Hari</MenuItem>
                        <MenuItem value='NET_30'>Net 30 Hari</MenuItem>
                        <MenuItem value='NET_60'>Net 60 Hari</MenuItem>
                        <MenuItem value='NET_90'>Net 90 Hari</MenuItem>
                      </CustomTextField>
                    )}
                  />
                </div>

                {/* Notes */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Catatan
                  </Typography>
                  <Controller
                    name='notes'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Catatan tambahan tentang vendor'
                        multiline
                        rows={3}
                      />
                    )}
                  />
                </div>

                {/* Sembunyikan */}
                <Button
                  variant='text'
                  color='primary'
                  size='small'
                  sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
                  onClick={() => setShowMore(false)}
                >
                  - Sembunyikan
                </Button>
              </>
            )}
          </div>
        </form>
      </Box>

      {/* Sticky Footer */}
      <Box
        sx={{
          position: 'sticky',
          bottom: 0,
          zIndex: 10,
          backgroundColor: 'background.paper',
          borderTop: 1,
          borderColor: 'divider',
          p: 3
        }}
      >
        <div className='flex items-center gap-4'>
          <Button variant='contained' type='submit' form='vendor-form' disabled={isSubmitting}>
            {isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
          </Button>
          <Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
            Batal
          </Button>
        </div>
      </Box>
    </Drawer>
  )
}

export default AddEditVendorDrawer
