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

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

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

// Services
import { useGamePrizesMutation } from '@/services/mutations/gamePrize'
import { useGames } from '@/services/queries/game'
import { GamePrize, GamePrizeRequest } from '@/types/services/gamePrize'
import { useGamePrizes } from '@/services/queries/gamePrize'

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

type FormValidateType = {
  game_id: string
  name: string
  weight: number
  stock: number
  max_stock?: number
  threshold?: number
  fallback_prize_id?: string
}

// Initial form data
const initialData: FormValidateType = {
  game_id: '',
  name: '',
  weight: 1,
  stock: 0,
  max_stock: 0,
  threshold: 0,
  fallback_prize_id: undefined
}

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

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

  // Queries
  const { data: gamesData } = useGames({ page: 1, limit: 100, search: '' })
  const { data: gamePrizesData } = useGamePrizes({ page: 1, limit: 100, search: '' })

  // Mutations
  const { createGamePrize, updateGamePrize } = useGamePrizesMutation()

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

  // Get available games and fallback prizes
  const games = gamesData?.data ?? []
  const availablePrizes = gamePrizesData?.data?.filter(prize => prize.id !== data?.id) ?? []

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

  const watchedMaxStock = watch('max_stock')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Populate form with existing data
      const formData: FormValidateType = {
        game_id: data.game_id || '',
        name: data.name || '',
        weight: data.weight || 1,
        stock: data.stock || 0,
        max_stock: data.max_stock,
        threshold: data.threshold,
        fallback_prize_id: data.fallback_prize_id
      }

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

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

      // Create GamePrizeRequest object
      const gamePrizeRequest: GamePrizeRequest = {
        game_id: formData.game_id,
        name: formData.name,
        weight: typeof formData.weight === 'string' ? parseFloat(formData.weight) : formData.weight || 1,
        stock: typeof formData.stock === 'string' ? parseInt(formData.stock, 10) : formData.stock || 0,
        max_stock: formData.max_stock
          ? typeof formData.max_stock === 'string'
            ? parseInt(formData.max_stock, 10)
            : formData.max_stock
          : undefined,
        threshold: formData.threshold
          ? typeof formData.threshold === 'string'
            ? parseInt(formData.threshold, 10)
            : formData.threshold
          : undefined,
        fallback_prize_id: formData.fallback_prize_id || undefined
      }

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

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

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{
        '& .MuiDrawer-paper': {
          width: { xs: 350, sm: 450 },
          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 Game' : 'Tambah Hadiah 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-prize-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Game Selection */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Pilih Game <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='game_id'
                control={control}
                rules={{ required: 'Game wajib dipilih' }}
                render={({ field: { onChange, value, ...field } }) => (
                  <CustomAutocomplete
                    {...field}
                    options={games}
                    getOptionLabel={option => `${option.name} (${option.type})`}
                    value={games.find(game => game.id === value) || null}
                    onChange={(_, newValue) => onChange(newValue?.id || '')}
                    disabled={isEditMode}
                    renderInput={params => (
                      <CustomTextField
                        {...params}
                        placeholder='Pilih game'
                        error={!!errors.game_id}
                        helperText={errors.game_id?.message}
                      />
                    )}
                    isOptionEqualToValue={(option, value) => option.id === value?.id}
                    noOptionsText='Tidak ada game tersedia'
                  />
                )}
              />
            </div>

            {/* 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>

            {/* Bobot */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Bobot <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='weight'
                control={control}
                rules={{
                  required: 'Bobot wajib diisi',
                  min: { value: 1, message: 'Bobot minimal 1' }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='Masukkan bobot hadiah'
                    error={!!errors.weight}
                    helperText={errors.weight?.message}
                    InputProps={{
                      endAdornment: <InputAdornment position='end'>%</InputAdornment>
                    }}
                    inputProps={{ min: 1, max: 100 }}
                  />
                )}
              />
            </div>

            {/* Stock */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Stok <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='stock'
                control={control}
                rules={{
                  required: 'Stok wajib diisi',
                  min: { value: 0, message: 'Stok minimal 0' },
                  validate: value => {
                    if (watchedMaxStock && value > watchedMaxStock) {
                      return 'Stok tidak boleh melebihi maksimal stok'
                    }
                    return true
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='Masukkan jumlah stok'
                    error={!!errors.stock}
                    helperText={errors.stock?.message}
                    inputProps={{ min: 0 }}
                  />
                )}
              />
            </div>

            {/* Max Stock */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Maksimal Stok
              </Typography>
              <Controller
                name='max_stock'
                control={control}
                rules={{
                  min: { value: 1, message: 'Maksimal stok minimal 1' }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='Masukkan maksimal stok (opsional)'
                    error={!!errors.max_stock}
                    helperText={errors.max_stock?.message}
                    inputProps={{ min: 1 }}
                  />
                )}
              />
            </div>

            {/* Threshold */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Threshold
              </Typography>
              <Controller
                name='threshold'
                control={control}
                rules={{
                  required: 'Threshold wajib diisi',
                  min: { value: 0, message: 'Threshold minimal 0' }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='Masukkan threshold '
                    error={!!errors.threshold}
                    helperText={errors.threshold?.message}
                    inputProps={{ min: 0 }}
                  />
                )}
              />
            </div>

            {/* Fallback Prize */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Hadiah Cadangan
              </Typography>
              <Controller
                name='fallback_prize_id'
                control={control}
                render={({ field: { onChange, value, ...field } }) => (
                  <CustomAutocomplete
                    {...field}
                    options={availablePrizes}
                    getOptionLabel={option => `${option.name} (Stok: ${option.stock})`}
                    value={availablePrizes.find(prize => prize.id === value) || null}
                    onChange={(_, newValue) => onChange(newValue?.id || '')}
                    renderInput={params => (
                      <CustomTextField
                        {...params}
                        placeholder='Pilih hadiah cadangan'
                        error={!!errors.fallback_prize_id}
                        helperText={
                          errors.fallback_prize_id?.message || 'Hadiah yang diberikan ketika hadiah ini habis'
                        }
                      />
                    )}
                    isOptionEqualToValue={(option, value) => option.id === value?.id}
                    noOptionsText='Tidak ada hadiah tersedia'
                    clearText='Hapus'
                  />
                )}
              />
            </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-prize-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 AddEditGamePrizeDrawer
