// 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 Box from '@mui/material/Box'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'

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

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

// Services
import { useFilesMutation } from '@/services/mutations/files'
import { Game, GameRequest } from '@/types/services/game'
import { useGamesMutation } from '@/services/mutations/game'

type Props = {
  open: boolean
  handleClose: () => void
  data?: Game // Game data for edit (if exists)
}

type FormValidateType = {
  name: string
  type: string
  is_active: boolean
  imageUrl: string
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  type: 'quiz',
  is_active: true,
  imageUrl: ''
}

// Mock mutation hooks (replace with actual hooks)

// Game types
const GAME_TYPES = [
  { value: 'SPIN', label: 'Spin' },
  { value: 'RUFFLE', label: 'Ruffle' },
  { value: 'MINIGAME', label: 'Mini Game' }
]

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

  // States
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>('')

  const { createGame, updateGame } = useGamesMutation()
  const { mutate, isPending } = useFilesMutation().uploadFile

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

  // Handle file upload
  const handleUpload = async (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('file_type', 'image')
      formData.append('description', 'game image upload')

      mutate(formData, {
        onSuccess: r => {
          setImageUrl(r.file_url)
          setValue('imageUrl', r.file_url) // Update form value
          resolve(r.id)
        },
        onError: er => {
          reject(er)
        }
      })
    })
  }

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

  const watchedImageUrl = watch('imageUrl')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Extract imageUrl from metadata
      const imageUrlFromData = data.metadata?.imageUrl || ''

      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        type: data.type || 'SPIN',
        is_active: data.is_active ?? true,
        imageUrl: imageUrlFromData
      }

      resetForm(formData)
      setImageUrl(imageUrlFromData)
    } else {
      // Reset to initial data for add mode
      resetForm(initialData)
      setImageUrl('')
    }
  }, [data, isEditMode, resetForm])

  // Sync imageUrl state with form value
  useEffect(() => {
    if (watchedImageUrl !== imageUrl) {
      setImageUrl(watchedImageUrl)
    }
  }, [watchedImageUrl, imageUrl])

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

      // Create GameRequest object
      const gameRequest: GameRequest = {
        name: formData.name,
        type: formData.type,
        is_active: formData.is_active,
        metadata: {
          imageUrl: formData.imageUrl || undefined
        }
      }

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

  const handleReset = () => {
    handleClose()
    resetForm(initialData)
    setImageUrl('')
  }

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

            {/* Tipe Game */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Tipe Game <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='type'
                control={control}
                rules={{ required: 'Tipe game wajib dipilih' }}
                render={({ field }) => (
                  <CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
                    {GAME_TYPES.map(type => (
                      <MenuItem key={type.value} value={type.value}>
                        {type.label}
                      </MenuItem>
                    ))}
                  </CustomTextField>
                )}
              />
            </div>

            {/* Image Upload */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Gambar Game
              </Typography>
              <ImageUpload
                onUpload={handleUpload}
                maxFileSize={1 * 1024 * 1024} // 1MB
                currentImageUrl={imageUrl}
                dragDropText='Drop your image here'
                browseButtonText='Choose Image'
              />
              <Controller
                name='imageUrl'
                control={control}
                render={({ field }) => <input type='hidden' {...field} value={imageUrl} />}
              />
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='is_active'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Game Aktif'
                  />
                )}
              />
            </div>
          </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='game-form' disabled={isSubmitting || isPending}>
            {isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
          </Button>
          <Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isPending}>
            Batal
          </Button>
        </div>
      </Box>
    </Drawer>
  )
}

export default AddEditGamesDrawer
