'use client'

import { useEffect } from 'react'
import Drawer from '@mui/material/Drawer'
import Button from '@/@core/components/mui/Button'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import CustomTextField from '@core/components/mui/TextField'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import CircularProgress from '@mui/material/CircularProgress'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'
import { Controller, useForm } from 'react-hook-form'
import { getImageUrl } from '@/utils'
import { IUpdateCategoryDto } from '@/types/data/categories/category-update.interface'
import { useGetCategory, useUpdateCategory } from '@/@core/hooks/data/categories/useUpdateAndDeleteCategory'
import { useGetCategoriesDropdown } from '@/@core/hooks/data/categories'
import { promptAndProcessImage } from '@/utils/imageCompression'
type Props = {
  open: boolean
  handleClose: () => void
  categoryId?: string
  onUpdated?: () => void
}

const EditCategoryDrawer = ({ open, handleClose, categoryId, onUpdated }: Props) => {
  const { data, isLoading } = useGetCategory(categoryId || '')
  const updateCategory = useUpdateCategory()

  const { data: dropdownCategories } = useGetCategoriesDropdown(
    { sort_by: 'sort_order', sort_as: 'asc' },
    { enabled: open }
  )

  const categories = Array.isArray(dropdownCategories) ? dropdownCategories : []

  const { control, handleSubmit, reset, setValue, watch } = useForm<IUpdateCategoryDto>({
    defaultValues: {
      name_ar: '',
      name_en: '',
      description_ar: '',
      description_en: '',
      sort_order: 1,
      parent_id: null,
      is_active: true,
      image: null
    }
  })

  const imageValue = watch('image')

  useEffect(() => {
    if (data) {
      const category = data
      reset({
        name_ar: category.name_ar,
        name_en: category.name_en,
        description_ar: category.description_ar ?? '',
        description_en: category.description_en ?? '',
        sort_order: category.sort_order ?? 1,
        parent_id: category.parent_id ?? null,
        is_active: category.is_active,
        image: category.image ?? category.image_url ?? null
      })
    }
  }, [data, reset])

  const handleFormSubmit = async (values: IUpdateCategoryDto) => {
    if (!categoryId) return
    await updateCategory.mutateAsync({ id: categoryId, payload: values })
    onUpdated?.()
    handleClose()
  }

  const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const processed = await promptAndProcessImage(file)
    if (!processed) {
      return
    }
    setValue('image', processed, { shouldDirty: true })
  }

  return (
    <Drawer
      anchor='right'
      open={open}
      onClose={handleClose}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 320, sm: 400 }, p: 4 } }}
    >
      <div className='flex justify-between items-center mb-4'>
        <Typography variant='h6'>تعديل الفئة</Typography>
        <IconButton onClick={handleClose}>
          <i className='tabler-x text-textSecondary' />
        </IconButton>
      </div>

      <Divider sx={{ mb: 4 }} />

      {isLoading ? (
        <div className='flex justify-center items-center h-full'>
          <CircularProgress />
        </div>
      ) : (
        <form onSubmit={handleSubmit(handleFormSubmit)} className='flex flex-col gap-4'>
          <Controller
            name='name_ar'
            control={control}
            render={({ field }) => <CustomTextField {...field} label='الاسم بالعربية' fullWidth />}
          />

          <Controller
            name='name_en'
            control={control}
            render={({ field }) => <CustomTextField {...field} label='الاسم بالإنجليزية' fullWidth />}
          />

          <Controller
            name='description_ar'
            control={control}
            render={({ field }) => <CustomTextField {...field} label='الوصف بالعربية' multiline rows={2} fullWidth />}
          />

          <Controller
            name='description_en'
            control={control}
            render={({ field }) => (
              <CustomTextField {...field} label='الوصف بالإنجليزية' multiline rows={2} fullWidth />
            )}
          />

          <Controller
            name='sort_order'
            control={control}
            render={({ field }) => <CustomTextField {...field} label='ترتيب العرض' type='number' fullWidth />}
          />

          <FormControl fullWidth>
            <InputLabel>الفئة الأب</InputLabel>
            <Controller
              name='parent_id'
              control={control}
              render={({ field }) => (
                <Select {...field} value={field.value ?? ''} onChange={e => field.onChange(e.target.value || null)}>
                  <MenuItem value=''>بدون أب</MenuItem>
                  {categories
                    .filter(cat => cat.id !== categoryId)
                    .map(cat => (
                      <MenuItem key={cat.id} value={cat.id}>
                        {cat.name_ar} ({cat.name_en})
                      </MenuItem>
                    ))}
                </Select>
              )}
            />
          </FormControl>

          <Controller
            name='is_active'
            control={control}
            render={({ field }) => (
              <FormControlLabel
                control={<Switch checked={field.value} onChange={(_, val) => field.onChange(val)} color='primary' />}
                label={field.value ? 'مفعّلة' : 'غير مفعّلة'}
              />
            )}
          />

          {/* ✅ عرض الصورة الحالية وتبديلها بطريقة جميلة */}
          <div className='flex flex-col gap-2'>
            <Typography variant='body2'>صورة الفئة</Typography>

            <div className='flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-xl p-4 hover:border-blue-400 transition-colors'>
              {!imageValue ? (
                <>
                  <label htmlFor='edit-upload-image' className='cursor-pointer flex flex-col items-center'>
                    <i className='tabler-upload text-3xl text-gray-400 mb-2' />
                    <Typography variant='body2' color='textSecondary'>
                      رفع صورة جديدة
                    </Typography>
                  </label>
                  <input
                    id='edit-upload-image'
                    type='file'
                    accept='image/*'
                    className='hidden'
                    onChange={handleImageChange}
                  />
                </>
              ) : (
                <div className='relative w-full flex flex-col items-center'>
                  <img
                    src={
                      typeof imageValue === 'string'
                        ? getImageUrl(imageValue)
                        : URL.createObjectURL(imageValue as File)
                    }
                    alt='Category'
                    className='w-full h-48 object-cover rounded-lg shadow-sm'
                  />

                  <div className='flex gap-2 mt-3'>
                    <Button variant='outlined' component='label'>
                      تبديل الصورة
                      <input type='file' accept='image/*' hidden onChange={handleImageChange} />
                    </Button>

                    <Button variant='outlined' color='error' onClick={() => setValue('image', null, { shouldDirty: true })}>
                      حذف الصورة
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className='flex justify-end gap-3 mt-4'>
            <Button variant='tonal' color='secondary' onClick={handleClose}>
              إلغاء
            </Button>
            <Button
              variant='contained'
              type='submit'
              disabled={updateCategory.isPending}
              isLoading={updateCategory.isPending}
            >
              {updateCategory.isPending ? 'جارٍ الحفظ...' : 'حفظ'}
            </Button>
          </div>
        </form>
      )}
    </Drawer>
  )
}

export default EditCategoryDrawer
