// 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
import { Campaign } from '@/types/services/campaign'
import { useCampaignsMutation } from '@/services/mutations/campaign'

// Updated Type Definitions
export type CampaignType = 'REWARD' | 'POINTS' | 'TOKENS' | 'MIXED'
export type RuleType = 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
export type RewardType = 'POINTS' | 'TOKENS' | 'REWARD'

export interface CampaignRequest {
  name: string
  description?: string
  type: CampaignType
  start_date: string // ISO string
  end_date: string // ISO string
  is_active: boolean
  show_on_app: boolean
  position: number
  metadata?: Record<string, any>
  rules: CampaignRuleRequest[]
}

export interface CampaignRuleRequest {
  rule_type: RuleType
  condition_value?: string
  reward_type: RewardType
  reward_value?: number
  reward_subtype?: string
}

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

type FormValidateType = {
  name: string
  description: string
  type: CampaignType
  start_date: string
  end_date: string
  is_active: boolean
  show_on_app: boolean
  position: number
  // Rules array
  rules: {
    rule_type: RuleType
    condition_value: string
    reward_type: RewardType
    reward_value: number
    reward_subtype: string
  }[]
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  description: '',
  type: 'POINTS',
  start_date: '',
  end_date: '',
  is_active: true,
  show_on_app: true,
  position: 1,
  // Initial rule
  rules: [
    {
      rule_type: 'SPEND',
      condition_value: '',
      reward_type: 'POINTS',
      reward_value: 0,
      reward_subtype: ''
    }
  ]
}

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

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

  const { createCampaign, updateCampaign } = useCampaignsMutation()

  // 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
  })

  // Field array for rules
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'rules'
  })

  const watchedStartDate = watch('start_date')
  const watchedEndDate = watch('end_date')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      const formData: FormValidateType = {
        name: data.name || '',
        description: data.description || '',
        type: data.type || 'POINTS',
        start_date: data.start_date ? new Date(data.start_date).toISOString().split('T')[0] : '',
        end_date: data.end_date ? new Date(data.end_date).toISOString().split('T')[0] : '',
        is_active: data.is_active ?? true,
        show_on_app: data.show_on_app ?? true,
        position: data.position || 1,
        // Map existing rules
        rules: data.rules?.map(rule => ({
          rule_type: rule.rule_type,
          condition_value: rule.condition_value || '',
          reward_type: rule.reward_type,
          reward_value: rule.reward_value || 0,
          reward_subtype: rule.reward_subtype || ''
        })) || [
          {
            rule_type: 'SPEND',
            condition_value: '',
            reward_type: 'POINTS',
            reward_value: 0,
            reward_subtype: ''
          }
        ]
      }

      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 rules array
      const rulesRequest: CampaignRuleRequest[] = formData.rules.map(rule => ({
        rule_type: rule.rule_type,
        condition_value: rule.condition_value || undefined,
        reward_type: rule.reward_type,
        reward_value: rule.reward_value || undefined,
        reward_subtype: rule.reward_subtype || undefined
      }))

      // Create metadata from rules if needed
      const metadata: Record<string, any> = {}
      const spendRule = formData.rules.find(rule => rule.rule_type === 'SPEND')
      if (spendRule?.condition_value) {
        metadata.minPurchase = parseInt(spendRule.condition_value)
      }

      // Create CampaignRequest object
      const campaignRequest: CampaignRequest = {
        name: formData.name,
        description: formData.description || undefined,
        type: formData.type,
        start_date: new Date(formData.start_date).toISOString(),
        end_date: new Date(formData.end_date).toISOString(),
        is_active: formData.is_active,
        show_on_app: formData.show_on_app,
        position: formData.position,
        metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
        rules: rulesRequest
      }

      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: RewardType) => {
    switch (type) {
      case 'POINTS':
        return 'Poin'
      case 'TOKENS':
        return 'Token'
      case 'REWARD':
        return 'Reward'
      default:
        return type
    }
  }

  const getRewardValuePlaceholder = (type: RewardType) => {
    switch (type) {
      case 'POINTS':
        return 'Jumlah poin yang diberikan'
      case 'TOKENS':
        return 'Jumlah token yang diberikan'
      case 'REWARD':
        return 'Nilai reward'
      default:
        return 'Nilai reward'
    }
  }

  const getConditionValuePlaceholder = (ruleType: RuleType) => {
    switch (ruleType) {
      case 'SPEND':
        return 'Minimum pembelian (Rupiah)'
      case 'TIER':
        return 'Tier pelanggan (misal: GOLD, SILVER)'
      case 'PRODUCT':
        return 'ID atau nama produk'
      case 'CATEGORY':
        return 'Kategori produk'
      case 'DAY':
        return 'Hari dalam seminggu (misal: MONDAY)'
      case 'LOCATION':
        return 'Lokasi atau kota'
      default:
        return 'Nilai kondisi'
    }
  }

  const getConditionValueInputProps = (ruleType: RuleType) => {
    if (ruleType === 'SPEND') {
      return {
        startAdornment: <InputAdornment position='start'>Rp</InputAdornment>,
        type: 'number' as const
      }
    }
    return { type: 'text' as const }
  }

  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>

            {/* Jenis Kampanye */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Jenis Kampanye <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='type'
                control={control}
                rules={{ required: 'Jenis kampanye wajib dipilih' }}
                render={({ field }) => (
                  <CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
                    <MenuItem value='POINTS'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-coins text-primary' />
                        Points
                      </div>
                    </MenuItem>
                    <MenuItem value='TOKENS'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-ticket text-success' />
                        Tokens
                      </div>
                    </MenuItem>
                    <MenuItem value='REWARD'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-gift text-warning' />
                        Reward
                      </div>
                    </MenuItem>
                    <MenuItem value='MIXED'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-layers-intersect text-info' />
                        Mixed
                      </div>
                    </MenuItem>
                  </CustomTextField>
                )}
              />
            </div>

            {/* Rules Section */}
            <div>
              <Box display='flex' alignItems='center' justifyContent='space-between' className='mb-4'>
                <Typography variant='h6'>Aturan Kampanye</Typography>
                <Button
                  variant='outlined'
                  size='small'
                  startIcon={<i className='tabler-plus' />}
                  onClick={() =>
                    append({
                      rule_type: 'SPEND',
                      condition_value: '',
                      reward_type: 'POINTS',
                      reward_value: 0,
                      reward_subtype: ''
                    })
                  }
                >
                  Tambah Aturan
                </Button>
              </Box>

              {fields.map((field, index) => (
                <Box key={field.id} className='mb-6 p-4 border border-gray-200 rounded-lg'>
                  <Box display='flex' alignItems='center' justifyContent='between' className='mb-3'>
                    <Typography variant='subtitle2' className='font-medium'>
                      Aturan {index + 1}
                    </Typography>
                    {fields.length > 1 && (
                      <IconButton size='small' color='error' onClick={() => remove(index)}>
                        <i className='tabler-trash text-lg' />
                      </IconButton>
                    )}
                  </Box>

                  <div className='flex flex-col gap-4'>
                    {/* Rule Type */}
                    <div>
                      <Typography variant='body2' className='mb-2'>
                        Tipe Aturan <span className='text-red-500'>*</span>
                      </Typography>
                      <Controller
                        name={`rules.${index}.rule_type`}
                        control={control}
                        rules={{ required: 'Tipe aturan wajib dipilih' }}
                        render={({ field }) => (
                          <CustomTextField
                            {...field}
                            select
                            fullWidth
                            size='small'
                            error={!!errors.rules?.[index]?.rule_type}
                            helperText={errors.rules?.[index]?.rule_type?.message}
                          >
                            <MenuItem value='SPEND'>Minimum Pembelian</MenuItem>
                            <MenuItem value='TIER'>Tier Pelanggan</MenuItem>
                            <MenuItem value='PRODUCT'>Produk Tertentu</MenuItem>
                            <MenuItem value='CATEGORY'>Kategori Produk</MenuItem>
                            <MenuItem value='DAY'>Hari Tertentu</MenuItem>
                            <MenuItem value='LOCATION'>Lokasi Tertentu</MenuItem>
                          </CustomTextField>
                        )}
                      />
                    </div>

                    {/* Condition Value */}
                    <div>
                      <Typography variant='body2' className='mb-2'>
                        Nilai Kondisi <span className='text-red-500'>*</span>
                      </Typography>
                      <Controller
                        name={`rules.${index}.condition_value`}
                        control={control}
                        rules={{ required: 'Nilai kondisi wajib diisi' }}
                        render={({ field }) => {
                          const ruleType = watch(`rules.${index}.rule_type`)
                          return (
                            <CustomTextField
                              {...field}
                              fullWidth
                              size='small'
                              placeholder={getConditionValuePlaceholder(ruleType)}
                              error={!!errors.rules?.[index]?.condition_value}
                              helperText={errors.rules?.[index]?.condition_value?.message}
                              InputProps={getConditionValueInputProps(ruleType)}
                              type={getConditionValueInputProps(ruleType).type}
                            />
                          )
                        }}
                      />
                    </div>

                    {/* Reward Type */}
                    <div>
                      <Typography variant='body2' className='mb-2'>
                        Jenis Reward <span className='text-red-500'>*</span>
                      </Typography>
                      <Controller
                        name={`rules.${index}.reward_type`}
                        control={control}
                        rules={{ required: 'Jenis reward wajib dipilih' }}
                        render={({ field }) => (
                          <CustomTextField
                            {...field}
                            select
                            fullWidth
                            size='small'
                            error={!!errors.rules?.[index]?.reward_type}
                            helperText={errors.rules?.[index]?.reward_type?.message}
                          >
                            <MenuItem value='POINTS'>
                              <div className='flex items-center gap-2'>
                                <i className='tabler-coins text-primary' />
                                Points
                              </div>
                            </MenuItem>
                            <MenuItem value='TOKENS'>
                              <div className='flex items-center gap-2'>
                                <i className='tabler-ticket text-success' />
                                Tokens
                              </div>
                            </MenuItem>
                            <MenuItem value='REWARD'>
                              <div className='flex items-center gap-2'>
                                <i className='tabler-percentage text-warning' />
                                Reward
                              </div>
                            </MenuItem>
                          </CustomTextField>
                        )}
                      />
                    </div>

                    {/* Reward Value */}
                    <div>
                      <Typography variant='body2' className='mb-2'>
                        Nilai Reward <span className='text-red-500'>*</span>
                      </Typography>
                      <Controller
                        name={`rules.${index}.reward_value`}
                        control={control}
                        rules={{
                          required: 'Nilai reward wajib diisi',
                          min: { value: 1, message: 'Nilai reward minimal 1' }
                        }}
                        render={({ field }) => {
                          const rewardType = watch(`rules.${index}.reward_type`)
                          return (
                            <CustomTextField
                              {...field}
                              fullWidth
                              size='small'
                              type='number'
                              placeholder={getRewardValuePlaceholder(rewardType)}
                              error={!!errors.rules?.[index]?.reward_value}
                              helperText={errors.rules?.[index]?.reward_value?.message}
                              InputProps={{
                                endAdornment:
                                  rewardType === 'POINTS' ? (
                                    <InputAdornment position='end'>Poin</InputAdornment>
                                  ) : rewardType === 'TOKENS' ? (
                                    <InputAdornment position='end'>Token</InputAdornment>
                                  ) : undefined
                              }}
                              onChange={e => field.onChange(Number(e.target.value))}
                            />
                          )
                        }}
                      />
                    </div>

                    {/* Reward Subtype (jika reward type adalah REWARD) */}
                    {watch(`rules.${index}.reward_type`) === 'REWARD' && (
                      <div>
                        <Typography variant='body2' className='mb-2'>
                          Sub-tipe Reward
                        </Typography>
                        <Controller
                          name={`rules.${index}.reward_subtype`}
                          control={control}
                          render={({ field }) => (
                            <CustomTextField {...field} select fullWidth size='small'>
                              <MenuItem value='DISCOUNT_PERCENT'>Diskon Persentase</MenuItem>
                              <MenuItem value='DISCOUNT_AMOUNT'>Diskon Nominal</MenuItem>
                              <MenuItem value='CASHBACK'>Cashback</MenuItem>
                              <MenuItem value='FREE_SHIPPING'>Gratis Ongkir</MenuItem>
                            </CustomTextField>
                          )}
                        />
                      </div>
                    )}
                  </div>
                </Box>
              ))}
            </div>

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

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

            {/* Show on App */}
            <div>
              <Controller
                name='show_on_app'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Tampilkan di Aplikasi'
                  />
                )}
              />
            </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>

                {/* Position */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Posisi Kampanye
                  </Typography>
                  <Controller
                    name='position'
                    control={control}
                    rules={{
                      min: { value: 1, message: 'Posisi minimal 1' }
                    }}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        type='number'
                        placeholder='Urutan tampilan kampanye'
                        error={!!errors.position}
                        helperText={errors.position?.message || 'Semakin kecil angka, semakin atas posisinya'}
                        onChange={e => field.onChange(Number(e.target.value))}
                      />
                    )}
                  />
                </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
