// 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'
import Chip from '@mui/material/Chip'
import InputAdornment from '@mui/material/InputAdornment'

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

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

// Types
export interface Campaign {
  id: string
  name: string
  description?: string
  minimumPurchase: number
  rewardType: 'point' | 'voucher' | 'discount'
  rewardValue: number
  startDate: Date
  endDate: Date
  isActive: boolean
  createdAt: Date
  updatedAt: Date
}

export interface CampaignRequest {
  name: string
  description?: string
  minimumPurchase: number
  rewardType: 'point' | 'voucher' | 'discount'
  rewardValue: number
  startDate: Date
  endDate: Date
  isActive: boolean
}

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

type FormValidateType = {
  name: string
  description: string
  minimumPurchase: number
  rewardType: 'point' | 'voucher' | 'discount'
  rewardValue: number
  startDate: string
  endDate: string
  isActive: boolean
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  description: '',
  minimumPurchase: 0,
  rewardType: 'point',
  rewardValue: 0,
  startDate: '',
  endDate: '',
  isActive: true
}

// Mock mutation hooks (replace with actual hooks)
const useCampaignMutation = () => {
  const createCampaign = {
    mutate: (data: CampaignRequest, options?: { onSuccess?: () => void }) => {
      console.log('Creating campaign:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

  const updateCampaign = {
    mutate: (data: { id: string; payload: CampaignRequest }, options?: { onSuccess?: () => void }) => {
      console.log('Updating campaign:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

  return { createCampaign, updateCampaign }
}

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

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

  const { createCampaign, updateCampaign } = useCampaignMutation()

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

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

  const watchedRewardType = watch('rewardType')
  const watchedStartDate = watch('startDate')
  const watchedEndDate = watch('endDate')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        description: data.description || '',
        minimumPurchase: data.minimumPurchase || 0,
        rewardType: data.rewardType || 'point',
        rewardValue: data.rewardValue || 0,
        startDate: data.startDate ? new Date(data.startDate).toISOString().split('T')[0] : '',
        endDate: data.endDate ? new Date(data.endDate).toISOString().split('T')[0] : '',
        isActive: data.isActive ?? true
      }

      resetForm(formData)
      setShowMore(true) // Always show more for edit mode
    } else {
      // Reset to initial data for add mode
      resetForm(initialData)
      setShowMore(false)
    }
  }, [data, isEditMode, resetForm])

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

      // Create CampaignRequest object
      const campaignRequest: CampaignRequest = {
        name: formData.name,
        description: formData.description || undefined,
        minimumPurchase: formData.minimumPurchase,
        rewardType: formData.rewardType,
        rewardValue: formData.rewardValue,
        startDate: new Date(formData.startDate),
        endDate: new Date(formData.endDate),
        isActive: formData.isActive
      }

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

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

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      minimumFractionDigits: 0
    }).format(value)
  }

  const getRewardTypeLabel = (type: 'point' | 'voucher' | 'discount') => {
    switch (type) {
      case 'point':
        return 'Poin'
      case 'voucher':
        return 'Voucher'
      case 'discount':
        return 'Diskon'
      default:
        return type
    }
  }

  const getRewardValuePlaceholder = (type: 'point' | 'voucher' | 'discount') => {
    switch (type) {
      case 'point':
        return 'Jumlah poin yang diberikan'
      case 'voucher':
        return 'Nilai voucher dalam Rupiah'
      case 'discount':
        return 'Persentase diskon (1-100)'
      default:
        return 'Nilai reward'
    }
  }

  const getRewardValueRules = (type: 'point' | 'voucher' | 'discount') => {
    const baseRules = {
      required: 'Nilai reward wajib diisi',
      min: {
        value: 1,
        message: 'Nilai reward minimal 1'
      }
    }

    if (type === 'discount') {
      return {
        ...baseRules,
        max: {
          value: 100,
          message: 'Persentase diskon maksimal 100%'
        }
      }
    }

    return baseRules
  }

  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 Kampanye' : 'Tambah Kampanye 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='campaign-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Nama Kampanye */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama Kampanye <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='name'
                control={control}
                rules={{ required: 'Nama kampanye wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Masukkan nama kampanye'
                    error={!!errors.name}
                    helperText={errors.name?.message}
                  />
                )}
              />
            </div>

            {/* Minimum Purchase */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Minimum Pembelian <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='minimumPurchase'
                control={control}
                rules={{
                  required: 'Minimum pembelian wajib diisi',
                  min: {
                    value: 0,
                    message: 'Minimum pembelian tidak boleh negatif'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='0'
                    error={!!errors.minimumPurchase}
                    helperText={errors.minimumPurchase?.message || (field.value > 0 ? formatCurrency(field.value) : '')}
                    InputProps={{
                      startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

            {/* Jenis Reward */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Jenis Reward <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='rewardType'
                control={control}
                rules={{ required: 'Jenis reward wajib dipilih' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    select
                    fullWidth
                    error={!!errors.rewardType}
                    helperText={errors.rewardType?.message}
                  >
                    <MenuItem value='point'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-coins text-primary' />
                        Poin
                      </div>
                    </MenuItem>
                    <MenuItem value='voucher'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-ticket text-success' />
                        Voucher
                      </div>
                    </MenuItem>
                    <MenuItem value='discount'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-percentage text-warning' />
                        Diskon
                      </div>
                    </MenuItem>
                  </CustomTextField>
                )}
              />
            </div>

            {/* Nilai Reward */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nilai {getRewardTypeLabel(watchedRewardType)} <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='rewardValue'
                control={control}
                rules={getRewardValueRules(watchedRewardType)}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder={getRewardValuePlaceholder(watchedRewardType)}
                    error={!!errors.rewardValue}
                    helperText={errors.rewardValue?.message}
                    InputProps={{
                      startAdornment:
                        watchedRewardType === 'voucher' ? (
                          <InputAdornment position='start'>Rp</InputAdornment>
                        ) : undefined,
                      endAdornment:
                        watchedRewardType === 'discount' ? (
                          <InputAdornment position='end'>%</InputAdornment>
                        ) : watchedRewardType === 'point' ? (
                          <InputAdornment position='end'>Poin</InputAdornment>
                        ) : undefined
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

            {/* Tanggal Mulai */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Tanggal Mulai <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='startDate'
                control={control}
                rules={{ required: 'Tanggal mulai wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='date'
                    error={!!errors.startDate}
                    helperText={errors.startDate?.message}
                    InputLabelProps={{
                      shrink: true
                    }}
                  />
                )}
              />
            </div>

            {/* Tanggal Berakhir */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Tanggal Berakhir <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='endDate'
                control={control}
                rules={{
                  required: 'Tanggal berakhir wajib diisi',
                  validate: value => {
                    if (watchedStartDate && value) {
                      return (
                        new Date(value) >= new Date(watchedStartDate) || 'Tanggal berakhir harus setelah tanggal mulai'
                      )
                    }
                    return true
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='date'
                    error={!!errors.endDate}
                    helperText={errors.endDate?.message}
                    InputLabelProps={{
                      shrink: true
                    }}
                    inputProps={{
                      min: watchedStartDate || undefined
                    }}
                  />
                )}
              />
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='isActive'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Kampanye 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 && (
              <>
                {/* Description */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Deskripsi Kampanye
                  </Typography>
                  <Controller
                    name='description'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Deskripsi detail tentang kampanye'
                        multiline
                        rows={4}
                      />
                    )}
                  />
                </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='campaign-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 AddEditCampaignDrawer
