// 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 LoyaltyType {
  id: string
  name: string
  minimumPurchase: number
  pointMultiplier: number
  benefits: string[]
  createdAt: Date
  updatedAt: Date
}

export interface LoyaltyRequest {
  name: string
  minimumPurchase: number
  pointMultiplier: number
  benefits: string[]
  description?: string
  isActive?: boolean
}

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

type FormValidateType = {
  name: string
  minimumPurchase: number
  pointMultiplier: number
  benefits: string[]
  description: string
  isActive: boolean
  newBenefit: string // Temporary field for adding new benefits
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  minimumPurchase: 0,
  pointMultiplier: 1,
  benefits: [],
  description: '',
  isActive: true,
  newBenefit: ''
}

// Mock mutation hooks (replace with actual hooks)
const useLoyaltyMutation = () => {
  const createLoyalty = {
    mutate: (data: LoyaltyRequest, options?: { onSuccess?: () => void }) => {
      console.log('Creating loyalty:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

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

  return { createLoyalty, updateLoyalty }
}

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

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

  const { createLoyalty, updateLoyalty } = useLoyaltyMutation()

  // 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 watchedBenefits = watch('benefits')
  const watchedNewBenefit = watch('newBenefit')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        minimumPurchase: data.minimumPurchase || 0,
        pointMultiplier: data.pointMultiplier || 1,
        benefits: data.benefits || [],
        description: '', // Add description field if available in your data
        isActive: true, // Add isActive field if available in your data
        newBenefit: ''
      }

      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 handleAddBenefit = () => {
    if (watchedNewBenefit.trim()) {
      const currentBenefits = watchedBenefits || []
      setValue('benefits', [...currentBenefits, watchedNewBenefit.trim()])
      setValue('newBenefit', '')
    }
  }

  const handleRemoveBenefit = (index: number) => {
    const currentBenefits = watchedBenefits || []
    const newBenefits = currentBenefits.filter((_, i) => i !== index)
    setValue('benefits', newBenefits)
  }

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      event.preventDefault()
      handleAddBenefit()
    }
  }

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

      // Create LoyaltyRequest object
      const loyaltyRequest: LoyaltyRequest = {
        name: formData.name,
        minimumPurchase: formData.minimumPurchase,
        pointMultiplier: formData.pointMultiplier,
        benefits: formData.benefits,
        description: formData.description || undefined,
        isActive: formData.isActive
      }

      if (isEditMode && data?.id) {
        // Update existing loyalty
        updateLoyalty.mutate(
          { id: data.id, payload: loyaltyRequest },
          {
            onSuccess: () => {
              handleReset()
              handleClose()
            }
          }
        )
      } else {
        // Create new loyalty
        createLoyalty.mutate(loyaltyRequest, {
          onSuccess: () => {
            handleReset()
            handleClose()
          }
        })
      }
    } catch (error) {
      console.error('Error submitting loyalty:', 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)
  }

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

            {/* Point Multiplier */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Pengali Poin <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='pointMultiplier'
                control={control}
                rules={{
                  required: 'Pengali poin wajib diisi',
                  min: {
                    value: 1,
                    message: 'Pengali poin minimal 1'
                  },
                  max: {
                    value: 10,
                    message: 'Pengali poin maksimal 10'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    select
                    fullWidth
                    error={!!errors.pointMultiplier}
                    helperText={errors.pointMultiplier?.message}
                    onChange={e => field.onChange(Number(e.target.value))}
                  >
                    {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(multiplier => (
                      <MenuItem key={multiplier} value={multiplier}>
                        {multiplier}x
                      </MenuItem>
                    ))}
                  </CustomTextField>
                )}
              />
            </div>

            {/* Benefits */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Manfaat Program <span className='text-red-500'>*</span>
              </Typography>

              {/* Display current benefits */}
              {watchedBenefits && watchedBenefits.length > 0 && (
                <div className='flex flex-wrap gap-2 mb-3'>
                  {watchedBenefits.map((benefit, index) => (
                    <Chip
                      key={index}
                      label={benefit}
                      onDelete={() => handleRemoveBenefit(index)}
                      color='primary'
                      variant='outlined'
                      size='small'
                    />
                  ))}
                </div>
              )}

              {/* Add new benefit */}
              <Controller
                name='newBenefit'
                control={control}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Tambah manfaat baru'
                    onKeyPress={handleKeyPress}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position='end'>
                          <Button size='small' onClick={handleAddBenefit} disabled={!watchedNewBenefit?.trim()}>
                            Tambah
                          </Button>
                        </InputAdornment>
                      )
                    }}
                  />
                )}
              />
              {(!watchedBenefits || watchedBenefits.length === 0) && (
                <Typography variant='caption' color='error'>
                  Minimal satu manfaat harus ditambahkan
                </Typography>
              )}
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='isActive'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Program 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 Program
                  </Typography>
                  <Controller
                    name='description'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Deskripsi detail tentang program loyalty'
                        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='loyalty-form'
            disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
          >
            {isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
          </Button>
          <Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
            Batal
          </Button>
        </div>
      </Box>
    </Drawer>
  )
}

export default AddEditLoyaltyDrawer
