// React Imports
import { useState } 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'

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

// Types Imports
import type { VendorType } from '@/types/apps/vendorTypes'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'

type Props = {
  open: boolean
  handleClose: () => void
  vendorData?: VendorType[]
  setData: (data: VendorType[]) => void
}

type FormValidateType = {
  name: string
  company: string
  email: string
  telephone: string
}

// Vars
const initialData = {
  name: '',
  company: '',
  email: '',
  telephone: ''
}

const AddVendorDrawer = (props: Props) => {
  // Props
  const { open, handleClose, vendorData, setData } = props

  // States
  const [showMore, setShowMore] = useState(false)
  const [alamatPengiriman, setAlamatPengiriman] = useState([''])
  const [rekeningBank, setRekeningBank] = useState([
    {
      bank: '',
      cabang: '',
      namaPemilik: '',
      nomorRekening: ''
    }
  ])
  const [showPemetaanAkun, setShowPemetaanAkun] = useState(false)

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

  // Functions untuk alamat
  const handleTambahAlamat = () => {
    setAlamatPengiriman([...alamatPengiriman, ''])
  }

  const handleHapusAlamat = (index: number) => {
    if (alamatPengiriman.length > 1) {
      const newAlamat = alamatPengiriman.filter((_, i) => i !== index)
      setAlamatPengiriman(newAlamat)
    }
  }

  const handleChangeAlamat = (index: number, value: string) => {
    const newAlamat = [...alamatPengiriman]
    newAlamat[index] = value
    setAlamatPengiriman(newAlamat)
  }

  // Functions untuk rekening bank
  const handleTambahRekening = () => {
    setRekeningBank([
      ...rekeningBank,
      {
        bank: '',
        cabang: '',
        namaPemilik: '',
        nomorRekening: ''
      }
    ])
  }

  const handleHapusRekening = (index: number) => {
    if (rekeningBank.length > 1) {
      const newRekening = rekeningBank.filter((_, i) => i !== index)
      setRekeningBank(newRekening)
    }
  }

  const handleChangeRekening = (index: number, field: string, value: string) => {
    const newRekening = [...rekeningBank]
    newRekening[index] = { ...newRekening[index], [field]: value }
    setRekeningBank(newRekening)
  }

  const onSubmit = (data: FormValidateType) => {
    const newVendor: VendorType = {
      id: (vendorData?.length && vendorData?.length + 1) || 1,
      photo: '',
      name: data.name,
      company: data.company,
      email: data.email,
      telephone: data.telephone,
      youPayable: 0,
      theyPayable: 0
    }

    setData([...(vendorData ?? []), newVendor])
    handleClose()
    resetForm(initialData)
    setAlamatPengiriman([''])
    setRekeningBank([
      {
        bank: '',
        cabang: '',
        namaPemilik: '',
        nomorRekening: ''
      }
    ])
    setShowMore(false)
    setShowPemetaanAkun(false)
  }

  const handleReset = () => {
    handleClose()
    resetForm(initialData)
    setAlamatPengiriman([''])
    setRekeningBank([
      {
        bank: '',
        cabang: '',
        namaPemilik: '',
        nomorRekening: ''
      }
    ])
    setShowMore(false)
    setShowPemetaanAkun(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'>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(data => onSubmit(data))}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Tampilkan Foto */}
            <div className='flex items-center gap-3'>
              <i className='tabler-plus text-blue-500' />
              <Typography variant='body1' color='primary' className='cursor-pointer'>
                Tampilkan Foto
              </Typography>
            </div>

            {/* Nama */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama <span className='text-red-500'>*</span>
              </Typography>
              <Grid container spacing={2}>
                <Grid size={4}>
                  <CustomTextField select fullWidth defaultValue='Tuan'>
                    <MenuItem value='Tuan'>Tuan</MenuItem>
                    <MenuItem value='Nyonya'>Nyonya</MenuItem>
                    <MenuItem value='Nona'>Nona</MenuItem>
                    <MenuItem value='Bapak'>Bapak</MenuItem>
                    <MenuItem value='Ibu'>Ibu</MenuItem>
                  </CustomTextField>
                </Grid>
                <Grid size={8}>
                  <Controller
                    name='name'
                    control={control}
                    rules={{ required: true }}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Nama'
                        {...(errors.name && { error: true, helperText: 'Field ini wajib diisi.' })}
                      />
                    )}
                  />
                </Grid>
              </Grid>
            </div>

            {/* Perusahaan dan Telepon */}
            <Grid container spacing={6}>
              <Grid size={6}>
                <Controller
                  name='company'
                  control={control}
                  rules={{ required: true }}
                  render={({ field }) => (
                    <CustomTextField
                      {...field}
                      fullWidth
                      label='Perusahaan'
                      placeholder='Perusahaan'
                      {...(errors.company && { error: true, helperText: 'Field ini wajib diisi.' })}
                    />
                  )}
                />
              </Grid>
              <Grid size={6}>
                <Controller
                  name='telephone'
                  control={control}
                  rules={{ required: true }}
                  render={({ field }) => (
                    <CustomTextField
                      {...field}
                      fullWidth
                      label='Telepon'
                      placeholder='Telepon'
                      {...(errors.telephone && { error: true, helperText: 'Field ini wajib diisi.' })}
                    />
                  )}
                />
              </Grid>
            </Grid>

            {/* Email */}
            <Controller
              name='email'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  type='email'
                  label='Email'
                  placeholder='Email'
                  {...(errors.email && { error: true, helperText: 'Field ini wajib diisi.' })}
                />
              )}
            />

            {/* Tampilkan selengkapnya */}
            {!showMore && (
              <div className='flex items-center gap-3' onClick={() => setShowMore(true)}>
                <i className='tabler-plus text-blue-500' />
                <Typography variant='body1' color='primary' className='cursor-pointer'>
                  Tampilkan selengkapnya
                </Typography>
              </div>
            )}

            {/* Konten tambahan yang muncul saat showMore true */}
            {showMore && (
              <>
                {/* Alamat Penagihan */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Alamat Penagihan
                  </Typography>
                  <CustomTextField fullWidth placeholder='Alamat Penagihan' multiline rows={3} />
                </div>

                {/* Negara */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Negara
                  </Typography>
                  <CustomTextField select fullWidth defaultValue='Indonesia'>
                    <MenuItem value='Indonesia'>Indonesia</MenuItem>
                  </CustomTextField>
                </div>

                {/* Provinsi dan Kota */}
                <Grid container spacing={6}>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      Provinsi
                    </Typography>
                    <CustomTextField select fullWidth placeholder='Provinsi'>
                      <MenuItem value=''>Pilih Provinsi</MenuItem>
                      <MenuItem value='DKI Jakarta'>DKI Jakarta</MenuItem>
                      <MenuItem value='Jawa Barat'>Jawa Barat</MenuItem>
                      <MenuItem value='Jawa Tengah'>Jawa Tengah</MenuItem>
                      <MenuItem value='Jawa Timur'>Jawa Timur</MenuItem>
                    </CustomTextField>
                  </Grid>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      Kota
                    </Typography>
                    <CustomTextField select fullWidth placeholder='Kota'>
                      <MenuItem value=''>Pilih Kota</MenuItem>
                      <MenuItem value='Jakarta'>Jakarta</MenuItem>
                      <MenuItem value='Bandung'>Bandung</MenuItem>
                      <MenuItem value='Surabaya'>Surabaya</MenuItem>
                    </CustomTextField>
                  </Grid>
                </Grid>

                {/* Kecamatan dan Kelurahan */}
                <Grid container spacing={6}>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      Kecamatan
                    </Typography>
                    <CustomTextField select fullWidth placeholder='Kecamatan'>
                      <MenuItem value=''>Pilih Kecamatan</MenuItem>
                    </CustomTextField>
                  </Grid>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      Kelurahan
                    </Typography>
                    <CustomTextField select fullWidth placeholder='Kelurahan'>
                      <MenuItem value=''>Pilih Kelurahan</MenuItem>
                    </CustomTextField>
                  </Grid>
                </Grid>

                {/* Tipe Kartu Identitas dan ID */}
                <Grid container spacing={6}>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      Tipe Kartu Identitas
                    </Typography>
                    <CustomTextField select fullWidth placeholder='Silahkan pilih tipe kartu identitas'>
                      <MenuItem value=''>Pilih Tipe Kartu Identitas</MenuItem>
                      <MenuItem value='KTP'>KTP</MenuItem>
                      <MenuItem value='SIM'>SIM</MenuItem>
                      <MenuItem value='Paspor'>Paspor</MenuItem>
                    </CustomTextField>
                  </Grid>
                  <Grid size={6}>
                    <Typography variant='body2' className='mb-2'>
                      ID Kartu Identitas
                    </Typography>
                    <CustomTextField fullWidth placeholder='ID Kartu Identitas' />
                  </Grid>
                </Grid>

                {/* NPWP */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    NPWP
                  </Typography>
                  <CustomTextField fullWidth placeholder='NPWP' />
                </div>

                {/* Alamat Pengiriman */}
                <div>
                  <Typography variant='body2' className='mb-2 font-medium'>
                    Alamat Pengiriman
                  </Typography>
                  {alamatPengiriman.map((alamat, index) => (
                    <div key={index} className='flex items-center gap-3 mb-3'>
                      <CustomTextField
                        fullWidth
                        placeholder='Alamat'
                        multiline
                        rows={2}
                        value={alamat}
                        onChange={e => handleChangeAlamat(index, e.target.value)}
                        sx={{
                          '& .MuiOutlinedInput-root': {
                            borderColor: index === 1 ? 'primary.main' : 'default'
                          }
                        }}
                      />
                      {alamatPengiriman.length > 1 && (
                        <IconButton
                          size='small'
                          onClick={() => handleHapusAlamat(index)}
                          sx={{
                            color: 'error.main',
                            border: 1,
                            borderColor: 'error.main',
                            '&:hover': {
                              backgroundColor: 'error.light',
                              borderColor: 'error.main'
                            }
                          }}
                        >
                          <i className='tabler-trash' />
                        </IconButton>
                      )}
                    </div>
                  ))}
                </div>

                {/* Tambah Alamat Pengiriman */}
                <div className='flex items-center gap-3' onClick={handleTambahAlamat}>
                  <i className='tabler-plus text-blue-500' />
                  <Typography variant='body1' color='primary' className='cursor-pointer'>
                    Tambah Alamat Pengiriman
                  </Typography>
                </div>

                {/* Rekening Bank */}
                <div>
                  <Typography variant='body2' className='mb-2 font-medium'>
                    Rekening Bank
                  </Typography>
                  {rekeningBank.map((rekening, index) => (
                    <div key={index} className='mb-4'>
                      <div className='flex items-start gap-3'>
                        <div className='flex-1'>
                          {/* Baris pertama: Bank & Cabang */}
                          <Grid container spacing={3} className='mb-3'>
                            <Grid size={6}>
                              <CustomTextField
                                select
                                fullWidth
                                placeholder='Bank'
                                value={rekening.bank}
                                onChange={e => handleChangeRekening(index, 'bank', e.target.value)}
                              >
                                <MenuItem value=''>Pilih Bank</MenuItem>
                                <MenuItem value='BCA'>BCA</MenuItem>
                                <MenuItem value='Mandiri'>Mandiri</MenuItem>
                                <MenuItem value='BNI'>BNI</MenuItem>
                                <MenuItem value='BRI'>BRI</MenuItem>
                              </CustomTextField>
                            </Grid>
                            <Grid size={6}>
                              <CustomTextField
                                fullWidth
                                placeholder='Cabang'
                                value={rekening.cabang}
                                onChange={e => handleChangeRekening(index, 'cabang', e.target.value)}
                              />
                            </Grid>
                          </Grid>

                          {/* Baris kedua: Nama Pemilik & Nomor Rekening */}
                          <Grid container spacing={3}>
                            <Grid size={6}>
                              <CustomTextField
                                fullWidth
                                placeholder='Nama Pemilik'
                                value={rekening.namaPemilik}
                                onChange={e => handleChangeRekening(index, 'namaPemilik', e.target.value)}
                              />
                            </Grid>
                            <Grid size={6}>
                              <CustomTextField
                                fullWidth
                                placeholder='Nomor Rekening'
                                value={rekening.nomorRekening}
                                onChange={e => handleChangeRekening(index, 'nomorRekening', e.target.value)}
                              />
                            </Grid>
                          </Grid>
                        </div>

                        {/* Tombol hapus di samping, sejajar dengan tengah kedua baris */}
                        {rekeningBank.length > 1 && (
                          <div className='flex items-center' style={{ height: '120px' }}>
                            <IconButton
                              size='small'
                              onClick={() => handleHapusRekening(index)}
                              sx={{
                                color: 'error.main',
                                border: 1,
                                borderColor: 'error.main',
                                '&:hover': {
                                  backgroundColor: 'error.light',
                                  borderColor: 'error.main'
                                }
                              }}
                            >
                              <i className='tabler-trash' />
                            </IconButton>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}

                  <div className='flex items-center gap-3 mt-4' onClick={handleTambahRekening}>
                    <i className='tabler-plus text-blue-500' />
                    <Typography variant='body1' color='primary' className='cursor-pointer'>
                      Tambah Rekening Bank
                    </Typography>
                  </div>

                  <div className='flex items-center gap-3 mt-2' onClick={() => setShowPemetaanAkun(!showPemetaanAkun)}>
                    <i className={showPemetaanAkun ? 'tabler-minus text-blue-500' : 'tabler-plus text-blue-500'} />
                    <Typography variant='body1' color='primary' className='cursor-pointer'>
                      {showPemetaanAkun ? 'Sembunyikan pemetaan akun' : 'Tampilkan pemetaan akun'}
                    </Typography>
                  </div>

                  {/* Konten Pemetaan Akun */}
                  {showPemetaanAkun && (
                    <div className='mt-6 p-4 border border-gray-200 rounded-lg'>
                      {/* Akun Hutang */}
                      <Grid container spacing={6} className='mb-4'>
                        <Grid size={6}>
                          <Typography variant='body2' className='mb-2 font-medium'>
                            Akun Hutang
                          </Typography>
                          <CustomTextField select fullWidth defaultValue='2-20100 Hutang Usaha'>
                            <MenuItem value='2-20100 Hutang Usaha'>2-20100 Hutang Usaha</MenuItem>
                            <MenuItem value='2-20200 Hutang Bank'>2-20200 Hutang Bank</MenuItem>
                            <MenuItem value='2-20300 Hutang Lainnya'>2-20300 Hutang Lainnya</MenuItem>
                          </CustomTextField>
                        </Grid>
                        <Grid size={6}>
                          <Typography variant='body2' className='mb-2 font-medium'>
                            Maksimal Hutang
                            <i className='tabler-help-circle text-gray-400 ml-1' />
                          </Typography>
                          <CustomTextField fullWidth type='number' defaultValue='0' placeholder='0' />
                        </Grid>
                      </Grid>

                      {/* Akun Piutang */}
                      <Grid container spacing={6} className='mb-4'>
                        <Grid size={6}>
                          <Typography variant='body2' className='mb-2 font-medium'>
                            Akun Piutang
                          </Typography>
                          <CustomTextField select fullWidth defaultValue='1-10100 Piutang Usaha'>
                            <MenuItem value='1-10100 Piutang Usaha'>1-10100 Piutang Usaha</MenuItem>
                            <MenuItem value='1-10200 Piutang Karyawan'>1-10200 Piutang Karyawan</MenuItem>
                            <MenuItem value='1-10300 Piutang Lainnya'>1-10300 Piutang Lainnya</MenuItem>
                          </CustomTextField>
                        </Grid>
                        <Grid size={6}>
                          <Typography variant='body2' className='mb-2 font-medium'>
                            Maksimal Piutang
                            <i className='tabler-help-circle text-gray-400 ml-1' />
                          </Typography>
                          <CustomTextField fullWidth type='number' defaultValue='0' placeholder='0' />
                        </Grid>
                      </Grid>

                      {/* Kena Pajak */}
                      <div className='mb-4'>
                        <Typography variant='body2' className='mb-3 font-medium'>
                          Kena pajak ?
                        </Typography>
                        <div className='flex items-center'>
                          <input
                            type='checkbox'
                            className='toggle-switch'
                            style={{
                              appearance: 'none',
                              width: '60px',
                              height: '30px',
                              backgroundColor: '#3b82f6',
                              borderRadius: '15px',
                              position: 'relative',
                              cursor: 'pointer',
                              outline: 'none'
                            }}
                          />
                          <style>
                            {`
                              .toggle-switch::before {
                                content: '';
                                position: absolute;
                                top: 3px;
                                left: 3px;
                                width: 24px;
                                height: 24px;
                                background-color: white;
                                border-radius: 50%;
                                transition: transform 0.3s ease;
                                transform: translateX(0);
                              }
                              .toggle-switch:checked::before {
                                transform: translateX(30px);
                              }
                            `}
                          </style>
                        </div>
                      </div>
                    </div>
                  )}

                  <Grid container spacing={6} className='mt-4'>
                    <Grid size={6}>
                      <Typography variant='body2' className='mb-2'>
                        Nomor
                      </Typography>
                      <CustomTextField fullWidth placeholder='Nomor' />
                    </Grid>
                    <Grid size={6}>
                      <Typography variant='body2' className='mb-2'>
                        Tanggal Lahir
                      </Typography>
                      <CustomTextField fullWidth type='date' placeholder='Tanggal Lahir' />
                    </Grid>
                  </Grid>

                  <div className='mt-4'>
                    <Typography variant='body2' className='mb-2'>
                      Deskripsi
                    </Typography>
                    <CustomTextField fullWidth placeholder='Deskripsi' multiline rows={3} />
                  </div>

                  {/* Button Sembunyikan di dalam konten */}
                  <div className='flex items-center gap-3 mt-6 mb-6' onClick={() => setShowMore(false)}>
                    <i className='tabler-minus text-blue-500' />
                    <Typography variant='body1' color='primary' className='cursor-pointer'>
                      Sembunyikan
                    </Typography>
                  </div>
                </div>
              </>
            )}
          </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'>
            Simpan
          </Button>
          <Button variant='tonal' color='error' onClick={() => handleReset()}>
            Batal
          </Button>
        </div>
      </Box>
    </Drawer>
  )
}

export default AddVendorDrawer
