// 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 Avatar from '@mui/material/Avatar'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import FormHelperText from '@mui/material/FormHelperText'
import TextField from '@mui/material/TextField'
import Accordion from '@mui/material/Accordion'
import AccordionSummary from '@mui/material/AccordionSummary'
import AccordionDetails from '@mui/material/AccordionDetails'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListItemText from '@mui/material/ListItemText'
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction'

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

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import MultipleImageUpload from '@/components/MultipleImageUpload' // Import the component

// Import the actual upload mutation
import { useFilesMutation } from '@/services/mutations/files'
import { useRewardsMutation } from '@/services/mutations/reward'

// Updated Types based on new API structure
export interface TermsAndConditions {
  sections: TncSection[]
  expiry_days: number
}

export interface TncSection {
  title: string
  rules: string[]
}

export interface RewardRequest {
  name: string // required, 1–150 chars
  reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL' // enum
  cost_points: number // min 1
  stock?: number
  max_per_customer: number // min 1
  tnc?: TermsAndConditions
  images?: string[] // Add images to request
}

export interface Reward {
  id: string // uuid
  name: string
  reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
  cost_points: number
  stock?: number
  max_per_customer: number
  tnc?: TermsAndConditions
  metadata?: Record<string, any>
  images?: string[]
  created_at: string // ISO date-time
  updated_at: string // ISO date-time
}

// Type for uploaded image in the component
type UploadedImage = {
  id: string
  url: string
  name: string
  size: number
}

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

type FormValidateType = {
  name: string
  reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
  cost_points: number
  stock: number | ''
  max_per_customer: number
  hasUnlimitedStock: boolean
  hasTnc: boolean
  tnc_expiry_days: number
  tnc_sections: TncSection[]
  uploadedImages: UploadedImage[] // Changed from images array to uploaded images
  metadata: Record<string, any>
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  reward_type: 'VOUCHER',
  cost_points: 100,
  stock: '',
  max_per_customer: 1,
  hasUnlimitedStock: false,
  hasTnc: false,
  tnc_expiry_days: 30,
  tnc_sections: [],
  uploadedImages: [], // Initialize as empty array
  metadata: {}
}

// Reward types
const REWARD_TYPES = [
  { value: 'VOUCHER', label: 'Voucher' },
  { value: 'PHYSICAL', label: 'Barang Fisik' },
  { value: 'DIGITAL', label: 'Digital' }
] as const

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

  // States
  const [showMore, setShowMore] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set())

  const { createReward, updateReward } = useRewardsMutation()
  const { mutate: uploadFile, isPending: isFileUploading } = useFilesMutation().uploadFile

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

  // Field arrays for dynamic sections
  const {
    fields: tncSectionFields,
    append: appendTncSection,
    remove: removeTncSection
  } = useFieldArray({
    control,
    name: 'tnc_sections'
  })

  const watchedUploadedImages = watch('uploadedImages')
  const watchedHasUnlimitedStock = watch('hasUnlimitedStock')
  const watchedHasTnc = watch('hasTnc')
  const watchedStock = watch('stock')
  const watchedCostPoints = watch('cost_points')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      // Convert existing images to UploadedImage format
      const existingImages: UploadedImage[] = (data.images || []).map((url, index) => ({
        id: `existing_${index}`,
        url: url,
        name: `Image ${index + 1}`,
        size: 0 // We don't have size info for existing images
      }))

      // Populate form with existing data
      const formData: FormValidateType = {
        name: data.name || '',
        reward_type: data.reward_type || 'VOUCHER',
        cost_points: data.cost_points || 100,
        stock: data.stock ?? '',
        max_per_customer: data.max_per_customer || 1,
        hasUnlimitedStock: data.stock === undefined || data.stock === null,
        hasTnc: Boolean(data.tnc),
        tnc_expiry_days: data.tnc?.expiry_days || 30,
        tnc_sections: data.tnc?.sections || [],
        uploadedImages: existingImages,
        metadata: data.metadata || {}
      }

      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])

  // Handle unlimited stock toggle
  useEffect(() => {
    if (watchedHasUnlimitedStock) {
      setValue('stock', '')
    }
  }, [watchedHasUnlimitedStock, setValue])

  // Image upload handlers
  const handleSingleUpload = async (file: File): Promise<string> => {
    const fileId = `${file.name}-${Date.now()}`

    return new Promise((resolve, reject) => {
      // Add file to uploading set
      setUploadingFiles(prev => new Set(prev).add(fileId))

      const formData = new FormData()
      formData.append('file', file)
      formData.append('file_type', 'image')
      formData.append('description', 'reward image upload')

      uploadFile(formData, {
        onSuccess: response => {
          // Remove file from uploading set
          setUploadingFiles(prev => {
            const newSet = new Set(prev)
            newSet.delete(fileId)
            return newSet
          })
          resolve(response.file_url)
        },
        onError: error => {
          // Remove file from uploading set
          setUploadingFiles(prev => {
            const newSet = new Set(prev)
            newSet.delete(fileId)
            return newSet
          })
          reject(error)
        }
      })
    })
  }

  const handleMultipleUpload = async (files: File[]): Promise<string[]> => {
    const uploadedUrls: string[] = []

    try {
      // Sequential upload to avoid overwhelming the server
      for (const file of files) {
        const url = await handleSingleUpload(file)
        uploadedUrls.push(url)
      }
      return uploadedUrls
    } catch (error) {
      console.error('Failed to upload images:', error)
      throw error
    }
  }

  const handleImagesChange = (images: UploadedImage[]) => {
    setValue('uploadedImages', images)
  }

  const handleImageRemove = (imageId: string) => {
    const currentImages = watchedUploadedImages || []
    const updatedImages = currentImages.filter(img => img.id !== imageId)
    setValue('uploadedImages', updatedImages)
  }

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

      // Extract image URLs from uploaded images
      const imageUrls = formData.uploadedImages.map(img => img.url)

      // Create RewardRequest object
      const rewardRequest: RewardRequest = {
        name: formData.name,
        reward_type: formData.reward_type,
        cost_points: formData.cost_points,
        stock: formData.hasUnlimitedStock ? undefined : (formData.stock as number) || undefined,
        max_per_customer: formData.max_per_customer,
        images: imageUrls.length > 0 ? imageUrls : undefined, // Include images in request
        tnc:
          formData.hasTnc && formData.tnc_sections.length > 0
            ? {
                sections: formData.tnc_sections,
                expiry_days: formData.tnc_expiry_days
              }
            : undefined
      }

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

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

  const formatPoints = (value: number) => {
    return value.toLocaleString('id-ID') + ' poin'
  }

  const getStockDisplay = () => {
    if (watchedHasUnlimitedStock) return 'Unlimited'
    if (watchedStock === '' || watchedStock === 0) return 'Tidak ada stok'
    return `${watchedStock} item`
  }

  const addTncSection = () => {
    appendTncSection({ title: '', rules: [''] })
  }

  // Check if any files are currently uploading
  const isAnyFileUploading = uploadingFiles.size > 0 || isFileUploading

  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 Reward' : 'Tambah Reward 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='reward-form' onSubmit={handleSubmit(handleFormSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Nama Reward */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Nama Reward <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='name'
                control={control}
                rules={{
                  required: 'Nama reward wajib diisi',
                  minLength: { value: 1, message: 'Nama reward minimal 1 karakter' },
                  maxLength: { value: 150, message: 'Nama reward maksimal 150 karakter' }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    placeholder='Masukkan nama reward'
                    error={!!errors.name}
                    helperText={errors.name?.message || `${field.value.length}/150 karakter`}
                  />
                )}
              />
            </div>

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

            {/* Cost Points */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Biaya Poin <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='cost_points'
                control={control}
                rules={{
                  required: 'Biaya poin wajib diisi',
                  min: {
                    value: 1,
                    message: 'Biaya poin minimal 1'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='100'
                    error={!!errors.cost_points}
                    helperText={errors.cost_points?.message || (field.value > 0 ? formatPoints(field.value) : '')}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position='start'>
                          <i className='tabler-star-filled text-warning' />
                        </InputAdornment>
                      )
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

            {/* Max Per Customer */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Maksimal per Pelanggan <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='max_per_customer'
                control={control}
                rules={{
                  required: 'Maksimal per pelanggan wajib diisi',
                  min: {
                    value: 1,
                    message: 'Minimal 1 per pelanggan'
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='number'
                    placeholder='1'
                    error={!!errors.max_per_customer}
                    helperText={errors.max_per_customer?.message}
                    InputProps={{
                      startAdornment: <InputAdornment position='start'>Max</InputAdornment>
                    }}
                    onChange={e => field.onChange(Number(e.target.value))}
                  />
                )}
              />
            </div>

            {/* Stock Management */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Manajemen Stok
              </Typography>
              <Controller
                name='hasUnlimitedStock'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Stok Unlimited'
                    className='mb-2'
                  />
                )}
              />
              {!watchedHasUnlimitedStock && (
                <Controller
                  name='stock'
                  control={control}
                  rules={{
                    required: !watchedHasUnlimitedStock ? 'Jumlah stok wajib diisi' : false,
                    min: {
                      value: 0,
                      message: 'Stok tidak boleh negatif'
                    }
                  }}
                  render={({ field }) => (
                    <CustomTextField
                      {...field}
                      fullWidth
                      type='number'
                      placeholder='0'
                      error={!!errors.stock}
                      helperText={errors.stock?.message || getStockDisplay()}
                      InputProps={{
                        startAdornment: <InputAdornment position='start'>Qty</InputAdornment>
                      }}
                      onChange={e => field.onChange(e.target.value ? Number(e.target.value) : '')}
                      value={field.value === '' ? '' : field.value}
                    />
                  )}
                />
              )}
            </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 && (
              <>
                {/* Multiple Image Upload Section */}
                <div>
                  <Typography variant='body2' className='mb-3'>
                    Gambar Reward
                  </Typography>
                  <MultipleImageUpload
                    title={null} // No title since we have our own
                    onUpload={handleMultipleUpload}
                    onSingleUpload={handleSingleUpload}
                    currentImages={watchedUploadedImages || []}
                    onImagesChange={handleImagesChange}
                    onImageRemove={handleImageRemove}
                    isUploading={isAnyFileUploading}
                    maxFiles={5}
                    maxFileSize={5 * 1024 * 1024} // 5MB
                    acceptedFileTypes={['image/jpeg', 'image/png', 'image/webp']}
                    showUrlOption={false}
                    uploadMode='individual'
                    uploadButtonText='Upload Gambar'
                    browseButtonText='Pilih Gambar'
                    dragDropText='Drag & drop gambar reward di sini'
                    replaceText='Drop gambar untuk menambah lebih banyak'
                    maxFilesText='Maksimal {max} gambar'
                    disabled={isSubmitting}
                  />
                  <FormHelperText>Format yang didukung: JPG, PNG, WebP. Maksimal 5MB per file.</FormHelperText>
                </div>

                {/* Terms & Conditions */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Syarat & Ketentuan
                  </Typography>
                  <Controller
                    name='hasTnc'
                    control={control}
                    render={({ field }) => (
                      <FormControlLabel
                        control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                        label='Memiliki syarat & ketentuan'
                        className='mb-2'
                      />
                    )}
                  />

                  {watchedHasTnc && (
                    <>
                      <Controller
                        name='tnc_expiry_days'
                        control={control}
                        rules={{
                          required: watchedHasTnc ? 'Masa berlaku T&C wajib diisi' : false,
                          min: { value: 1, message: 'Minimal 1 hari' }
                        }}
                        render={({ field }) => (
                          <CustomTextField
                            {...field}
                            fullWidth
                            type='number'
                            label='Masa Berlaku T&C (hari)'
                            placeholder='30'
                            error={!!errors.tnc_expiry_days}
                            helperText={errors.tnc_expiry_days?.message}
                            className='mb-4'
                            onChange={e => field.onChange(Number(e.target.value))}
                          />
                        )}
                      />

                      {tncSectionFields.map((section, sectionIndex) => (
                        <Accordion key={section.id} className='mb-2'>
                          <AccordionSummary expandIcon={<i className='tabler-chevron-down' />}>
                            <Typography>Bagian {sectionIndex + 1}</Typography>
                          </AccordionSummary>
                          <AccordionDetails>
                            <Controller
                              name={`tnc_sections.${sectionIndex}.title`}
                              control={control}
                              rules={{ required: 'Judul bagian wajib diisi' }}
                              render={({ field }) => (
                                <CustomTextField
                                  {...field}
                                  fullWidth
                                  label='Judul Bagian'
                                  placeholder='Judul bagian'
                                  className='mb-2'
                                />
                              )}
                            />

                            <Typography variant='body2' className='mb-2'>
                              Aturan:
                            </Typography>
                            {section.rules?.map((rule, ruleIndex) => (
                              <Controller
                                key={ruleIndex}
                                name={`tnc_sections.${sectionIndex}.rules.${ruleIndex}`}
                                control={control}
                                render={({ field }) => (
                                  <CustomTextField
                                    {...field}
                                    fullWidth
                                    placeholder={`Aturan ${ruleIndex + 1}`}
                                    className='mb-1'
                                    multiline
                                    rows={2}
                                  />
                                )}
                              />
                            ))}

                            <Box className='flex gap-2 mt-2'>
                              <Button
                                size='small'
                                onClick={() => {
                                  const currentSection = watch(`tnc_sections.${sectionIndex}`)
                                  setValue(`tnc_sections.${sectionIndex}.rules`, [...(currentSection.rules || []), ''])
                                }}
                              >
                                + Aturan
                              </Button>
                              <Button size='small' color='error' onClick={() => removeTncSection(sectionIndex)}>
                                Hapus Bagian
                              </Button>
                            </Box>
                          </AccordionDetails>
                        </Accordion>
                      ))}

                      <Button
                        variant='outlined'
                        size='small'
                        onClick={addTncSection}
                        startIcon={<i className='tabler-plus' />}
                        className='mb-4'
                      >
                        Tambah Bagian T&C
                      </Button>
                    </>
                  )}
                </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='reward-form' disabled={isSubmitting || isAnyFileUploading}>
            {isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
          </Button>
          <Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isAnyFileUploading}>
            Batal
          </Button>
        </div>
        {isAnyFileUploading && (
          <Typography variant='caption' color='textSecondary' className='mt-2'>
            Sedang mengupload gambar... ({uploadingFiles.size} file)
          </Typography>
        )}
      </Box>
    </Drawer>
  )
}

export default AddEditRewardDrawer
