// 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 type TierType = {
  id: string // uuid
  name: string
  min_points: number
  benefits: Record<string, any>
  created_at: string // ISO datetime
  updated_at: string // ISO datetime
}

export interface TierRequest {
  name: string
  min_points: number
  benefits: Record<string, any>
}

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

type FormValidateType = {
  name: string
  min_points: number
  benefits: string[] // Array of benefit names for easier form handling
  newBenefit: string // Temporary field for adding new benefits
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  min_points: 0,
  benefits: [],
  newBenefit: ''
}

// Mock mutation hooks (replace with actual hooks)
const useTierMutation = () => {
  const createTier = {
    mutate: (data: TierRequest, options?: { onSuccess?: () => void }) => {
      console.log('Creating tier:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

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

  return { createTier, updateTier }
}

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

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

  const { createTier, updateTier } = useTierMutation()

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

  // Helper function to convert benefits object to string array
  const convertBenefitsToArray = (benefits: Record<string, any>): string[] => {
    if (!benefits) return []
    return Object.keys(benefits).filter(key => benefits[key] === true || benefits[key] === 'true')
  }

  // Helper function to convert benefits array to object
  const convertBenefitsToObject = (benefits: string[]): Record<string, any> => {
    const benefitsObj: Record<string, any> = {}
    benefits.forEach(benefit => {
      benefitsObj[benefit] = true
    })
    return benefitsObj
  }

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Convert benefits object to array for form handling
      const benefitsArray = convertBenefitsToArray(data.benefits)

      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        min_points: data.min_points || 0,
        benefits: benefitsArray,
        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)

      // Convert benefits array back to object format
      const benefitsObj = convertBenefitsToObject(formData.benefits)

      // Create TierRequest object
      const tierRequest: TierRequest = {
        name: formData.name,
        min_points: formData.min_points,
        benefits: benefitsObj
      }

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

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

  const formatNumber = (value: number) => {
    return new Intl.NumberFormat('id-ID').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 Tier' : 'Tambah Tier 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='tier-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Nama Tier */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama Tier <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='name'
                control={control}
                rules={{ required: 'Nama tier wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Masukkan nama tier (contoh: Bronze, Silver, Gold)'
                    error={!!errors.name}
                    helperText={errors.name?.message}
                  />
                )}
              />
            </div>

            {/* Minimum Points */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Minimum Poin <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='min_points'
                control={control}
                rules={{
                  required: 'Minimum poin wajib diisi',
                  min: {
                    value: 0,
                    message: 'Minimum poin tidak boleh negatif'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='0'
                    error={!!errors.min_points}
                    helperText={
                      errors.min_points?.message || (field.value > 0 ? `${formatNumber(field.value)} poin` : '')
                    }
                    InputProps={{
                      endAdornment: <InputAdornment position='end'>poin</InputAdornment>
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

            {/* Benefits */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Manfaat Tier <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 (contoh: Diskon 10%, Akses VIP)'
                    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>

            {/* 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 && (
              <>
                {/* 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='tier-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 AddEditTierDrawer
