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

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

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

// Types
export interface WheelSpinType {
  id: string
  name: string
  weight: number
  omset: number
  fallback: boolean
  stock?: number
  createdAt: Date
  updatedAt: Date
}

export interface WheelSpinRequest {
  name: string
  weight: number
  omset: number
  fallback: boolean
  stock?: number
  description?: string
  isActive?: boolean
}

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

type FormValidateType = {
  name: string
  weight: number
  omset: number
  fallback: boolean
  stock?: number
  description: string
  isActive: boolean
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  weight: 10,
  omset: 0,
  fallback: false,
  stock: undefined,
  description: '',
  isActive: true
}

// Mock mutation hooks (replace with actual hooks)
const useWheelSpinMutation = () => {
  const createWheelSpin = {
    mutate: (data: WheelSpinRequest, options?: { onSuccess?: () => void }) => {
      console.log('Creating wheel spin:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

  const updateWheelSpin = {
    mutate: (data: { id: string; payload: WheelSpinRequest }, options?: { onSuccess?: () => void }) => {
      console.log('Updating wheel spin:', data)
      setTimeout(() => options?.onSuccess?.(), 1000)
    }
  }

  return { createWheelSpin, updateWheelSpin }
}

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

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

  const { createWheelSpin, updateWheelSpin } = useWheelSpinMutation()

  // 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 watchedFallback = watch('fallback')
  const watchedStock = watch('stock')
  const watchedWeight = watch('weight')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        weight: data.weight || 10,
        omset: data.omset || 0,
        fallback: data.fallback || false,
        stock: data.stock,
        description: '', // Add description field if available in your data
        isActive: true // Add isActive field if available in your data
      }

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

  // Handle stock toggle
  const handleStockToggle = (checked: boolean) => {
    setHasStock(checked)
    if (!checked) {
      setValue('stock', undefined)
    } else {
      setValue('stock', 0)
    }
  }

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

      // Create WheelSpinRequest object
      const wheelSpinRequest: WheelSpinRequest = {
        name: formData.name,
        weight: formData.weight,
        omset: formData.omset,
        fallback: formData.fallback,
        stock: hasStock ? formData.stock : undefined,
        description: formData.description || undefined,
        isActive: formData.isActive
      }

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

  const handleReset = () => {
    handleClose()
    resetForm(initialData)
    setShowMore(false)
    setHasStock(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 Hadiah Wheel Spin' : 'Tambah Hadiah 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='wheel-spin-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Nama Hadiah */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama Hadiah <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='name'
                control={control}
                rules={{ required: 'Nama hadiah wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Masukkan nama hadiah'
                    error={!!errors.name}
                    helperText={errors.name?.message}
                  />
                )}
              />
            </div>

            {/* Weight */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Bobot Kemunculan <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='weight'
                control={control}
                rules={{
                  required: 'Bobot wajib diisi',
                  min: {
                    value: 1,
                    message: 'Bobot minimal 1%'
                  },
                  max: {
                    value: 100,
                    message: 'Bobot maksimal 100%'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='10'
                    error={!!errors.weight}
                    helperText={errors.weight?.message || `Peluang kemunculan: ${watchedWeight}%`}
                    InputProps={{
                      endAdornment: <InputAdornment position='end'>%</InputAdornment>
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

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

            {/* Fallback Option */}
            <div>
              <Controller
                name='fallback'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='warning' />}
                    label='Hadiah Fallback'
                  />
                )}
              />
              {watchedFallback && (
                <Alert severity='info' sx={{ mt: 1 }}>
                  Hadiah fallback akan muncul ketika hadiah lain tidak tersedia atau habis
                </Alert>
              )}
            </div>

            {/* Stock Management */}
            <div>
              <FormControlLabel
                control={
                  <Switch checked={hasStock} onChange={e => handleStockToggle(e.target.checked)} color='primary' />
                }
                label='Batasi Stok'
              />

              {hasStock && (
                <div className='mt-3'>
                  <Typography variant='body2' className='mb-2'>
                    Jumlah Stok <span className='text-red-500'>*</span>
                  </Typography>
                  <Controller
                    name='stock'
                    control={control}
                    rules={
                      hasStock
                        ? {
                            required: 'Jumlah stok wajib diisi',
                            min: {
                              value: 0,
                              message: 'Stok tidak boleh negatif'
                            }
                          }
                        : {}
                    }
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        type='number'
                        placeholder='0'
                        error={!!errors.stock}
                        helperText={errors.stock?.message || 'Kosongkan untuk stok unlimited'}
                        onChange={e => field.onChange(Number(e.target.value))}
                      />
                    )}
                  />
                </div>
              )}
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='isActive'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Hadiah 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 Hadiah
                  </Typography>
                  <Controller
                    name='description'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Deskripsi detail tentang hadiah ini'
                        multiline
                        rows={4}
                      />
                    )}
                  />
                </div>

                {/* Tips */}
                <Alert severity='info'>
                  <Typography variant='body2'>
                    <strong>Tips:</strong>
                    <br />
                    • Bobot yang lebih tinggi = peluang menang lebih besar
                    <br />
                    • Hadiah fallback sebaiknya selalu ada untuk backup
                    <br />• Minimum omset membantu mendorong transaksi lebih besar
                  </Typography>
                </Alert>

                {/* 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='wheel-spin-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 AddEditWheelSpinDrawer
