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

// Types
import { Campaign, CampaignRequest, CampaignType } from '@/types/services/campaign'
import { useCampaignsMutation } from '@/services/mutations/campaign'
import { useFilesMutation } from '@/services/mutations/files'
import { formatDateYYYYMMDD } from '@/utils/transform'

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

type FormValidateType = {
  name: string
  description: string
  type: CampaignType
  start_date: string
  end_date: string
  is_active: boolean
  show_on_app: boolean
  position: number
  banner_url: string
}

// Initial form data
const initialData: FormValidateType = {
  name: '',
  description: '',
  type: 'POINTS',
  start_date: '',
  end_date: '',
  is_active: true,
  show_on_app: true,
  position: 1,
  banner_url: ''
}

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

  // States
  const [showMore, setShowMore] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [bannerUrl, setBannerUrl] = useState<string>('')

  const { createCampaign, updateCampaign } = useCampaignsMutation()
  const { mutate: uploadFile, isPending: isUploadPending } = 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
  })

  const watchedStartDate = watch('start_date')
  const watchedEndDate = watch('end_date')

  // Effect to populate form when editing
  useEffect(() => {
    if (isEditMode && data) {
      const formData: FormValidateType = {
        name: data.name || '',
        description: data.description || '',
        type: data.type || 'POINTS',
        start_date: data.start_date ? new Date(data.start_date).toISOString().split('T')[0] : '',
        end_date: data.end_date ? new Date(data.end_date).toISOString().split('T')[0] : '',
        is_active: data.is_active ?? true,
        show_on_app: data.show_on_app ?? true,
        position: data.position || 1,
        banner_url: data.metadata?.banner_url || ''
      }

      resetForm(formData)
      setBannerUrl(data.metadata?.banner_url || '')
      setShowMore(true) // Always show more for edit mode
    } else {
      // Reset to initial data for add mode
      resetForm(initialData)
      setBannerUrl('')
      setShowMore(false)
    }
  }, [data, isEditMode, resetForm])

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

      // Create metadata object
      const metadata: { banner_url?: string } = {}
      if (bannerUrl.trim()) {
        metadata.banner_url = bannerUrl.trim()
      }

      // Create CampaignRequest object
      const campaignRequest: CampaignRequest = {
        name: formData.name,
        description: formData.description || undefined,
        type: formData.type,
        start_date: formatDateYYYYMMDD(formData.start_date),
        end_date: formatDateYYYYMMDD(formData.end_date),
        is_active: formData.is_active,
        show_on_app: formData.show_on_app,
        position: formData.position,
        metadata: Object.keys(metadata).length > 0 ? metadata : undefined
      }

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

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

  // Handle file upload
  const handleBannerUpload = 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', 'campaign banner upload')

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

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

            {/* Jenis Kampanye */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Jenis Kampanye <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='type'
                control={control}
                rules={{ required: 'Jenis kampanye wajib dipilih' }}
                render={({ field }) => (
                  <CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
                    <MenuItem value='POINTS'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-coins text-primary' />
                        Points
                      </div>
                    </MenuItem>
                    <MenuItem value='TOKENS'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-ticket text-success' />
                        Tokens
                      </div>
                    </MenuItem>
                    <MenuItem value='REWARD'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-gift text-warning' />
                        Reward
                      </div>
                    </MenuItem>
                    <MenuItem value='MIXED'>
                      <div className='flex items-center gap-2'>
                        <i className='tabler-layers-intersect text-info' />
                        Mixed
                      </div>
                    </MenuItem>
                  </CustomTextField>
                )}
              />
            </div>

            {/* Tanggal Mulai */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Tanggal Mulai <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='start_date'
                control={control}
                rules={{ required: 'Tanggal mulai wajib diisi' }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='date'
                    error={!!errors.start_date}
                    helperText={errors.start_date?.message}
                    InputLabelProps={{
                      shrink: true
                    }}
                  />
                )}
              />
            </div>

            {/* Tanggal Berakhir */}
            <div>
              <Typography variant='body2' className='mb-2'>
                Tanggal Berakhir <span className='text-red-500'>*</span>
              </Typography>
              <Controller
                name='end_date'
                control={control}
                rules={{
                  required: 'Tanggal berakhir wajib diisi',
                  validate: value => {
                    if (watchedStartDate && value) {
                      return (
                        new Date(value) >= new Date(watchedStartDate) || 'Tanggal berakhir harus setelah tanggal mulai'
                      )
                    }
                    return true
                  }
                }}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    type='date'
                    error={!!errors.end_date}
                    helperText={errors.end_date?.message}
                    InputLabelProps={{
                      shrink: true
                    }}
                    inputProps={{
                      min: watchedStartDate || undefined
                    }}
                  />
                )}
              />
            </div>

            {/* Status Aktif */}
            <div>
              <Controller
                name='is_active'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Kampanye Aktif'
                  />
                )}
              />
            </div>

            {/* Show on App */}
            <div>
              <Controller
                name='show_on_app'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
                    label='Tampilkan di Aplikasi'
                  />
                )}
              />
            </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 Kampanye
                  </Typography>
                  <Controller
                    name='description'
                    control={control}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        placeholder='Deskripsi detail tentang kampanye'
                        multiline
                        rows={4}
                      />
                    )}
                  />
                </div>

                {/* Banner Upload */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Banner Kampanye
                  </Typography>
                  <ImageUpload
                    onUpload={handleBannerUpload}
                    maxFileSize={1 * 1024 * 1024} // 1MB
                    currentImageUrl={bannerUrl}
                    dragDropText='Drop banner image here'
                    browseButtonText='Choose Banner'
                  />
                  <Typography variant='caption' color='text.secondary' className='mt-1 block'>
                    Format: JPG, PNG. Ukuran maksimal: 1MB
                  </Typography>
                </div>

                {/* Position */}
                <div>
                  <Typography variant='body2' className='mb-2'>
                    Posisi Kampanye
                  </Typography>
                  <Controller
                    name='position'
                    control={control}
                    rules={{
                      min: { value: 1, message: 'Posisi minimal 1' }
                    }}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        fullWidth
                        type='number'
                        placeholder='Urutan tampilan kampanye'
                        error={!!errors.position}
                        helperText={errors.position?.message || 'Semakin kecil angka, semakin atas posisinya'}
                        onChange={e => field.onChange(Number(e.target.value))}
                      />
                    )}
                  />
                </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='campaign-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 AddEditCampaignDrawer
