'use client'

import { useTranslations } from 'next-intl'
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 { Controller, useForm } from 'react-hook-form'
import { useEffect } from 'react'
import { toast } from 'react-toastify'
import { useAddCategory, useGetCategoriesDropdown } from '@/@core/hooks/data/categories'
import type { ICreateCategoryDto } from '@/types/data/categories/category-create.interface'
import type { ICategory } from '@/types/data/categories/category.interface'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import { promptAndProcessImage } from '@/utils/imageCompression'
import { getImageUrl } from '@/utils'

type Props = {
  open: boolean
  handleClose: () => void
  onAdded?: () => void
  parentId?: string | null
  disableParentSelection?: boolean
}

const AddCategoryDrawer = ({ open, handleClose, onAdded, parentId = null, disableParentSelection = false }: Props) => {
  const t = useTranslations('categories')
  const detailsT = useTranslations('categories.details')

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

  useEffect(() => {
    setValue('parent_id', parentId ?? null)
  }, [parentId, setValue])

  const addCategory = useAddCategory()

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

  const categories = disableParentSelection ? [] : Array.isArray(dropdownCategories) ? dropdownCategories : []
  const imageValue = watch('image')

  const renderCategoryOptions = (cats: ICategory[], level = 0): JSX.Element[] => {
    if (!Array.isArray(cats)) return []

    return cats.reduce<JSX.Element[]>((acc, cat) => {
      acc.push(
        <MenuItem key={`${cat.id}-${level}`} value={cat.id}>
          {'--'.repeat(level)}
          {cat.name_ar} ({cat.name_en})
        </MenuItem>
      )

      if (Array.isArray(cat.children) && cat.children.length > 0) {
        acc.push(...renderCategoryOptions(cat.children, level + 1))
      }

      return acc
    }, [])
  }

  const handleFormSubmit = async (values: ICreateCategoryDto) => {
    try {
      const dto: ICreateCategoryDto = {
        ...values,
        sort_order: Number(values.sort_order),
        image: values.image ?? null,
        is_active: values.is_active ? 1 : 0
      }

      const res = await addCategory.mutateAsync(dto)
      reset()

      onAdded?.()
      handleClose()
    } catch (error) {
      console.error('Error adding category:', error)
    }
  }

  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'>{t('addTitle')}</Typography>
        <IconButton onClick={handleClose}>
          <i className='tabler-x text-textSecondary' />
        </IconButton>
      </div>
      <Divider sx={{ mb: 4 }} />

      <form onSubmit={handleSubmit(handleFormSubmit)} className='flex flex-col gap-4'>
        <Controller
          name='name_ar'
          control={control}
          rules={{ required: true }}
          render={({ field }) => <CustomTextField {...field} label={t('arabicName')} fullWidth />}
        />

        <Controller
          name='name_en'
          control={control}
          rules={{ required: true }}
          render={({ field }) => <CustomTextField {...field} label={t('englishName')} fullWidth />}
        />

        <Controller
          name='description_ar'
          control={control}
          render={({ field }) => <CustomTextField {...field} label={t('arabicDesc')} multiline rows={3} fullWidth />}
        />

        <Controller
          name='description_en'
          control={control}
          render={({ field }) => <CustomTextField {...field} label={t('englishDesc')} multiline rows={3} fullWidth />}
        />

        <Controller
          name='sort_order'
          control={control}
          render={({ field }) => <CustomTextField {...field} label={t('sortOrder')} type='number' fullWidth />}
        />

        {!disableParentSelection && (
          <FormControl fullWidth>
            <InputLabel>{detailsT('parentCategory')}</InputLabel>
            <Controller
              name='parent_id'
              control={control}
              render={({ field }) => (
                <Select
                  {...field}
                  value={field.value ?? ''}
                  onChange={e => field.onChange(e.target.value || null)}
                  MenuProps={{
                    disablePortal: true,
                    PaperProps: {
                      style: {
                        maxHeight: 300,
                        overflowY: 'auto',
                        borderRadius: 10
                      }
                    },
                    MenuListProps: {
                      style: {
                        padding: 0
                      }
                    }
                  }}
                >
                  <MenuItem value=''>{detailsT('noParent')}</MenuItem>
                  {renderCategoryOptions(categories)}
                </Select>
              )}
            />
          </FormControl>
        )}

        <Controller
          name='is_active'
          control={control}
          render={({ field }) => (
            <FormControlLabel
              control={
                <Switch
                  {...field}
                  checked={field.value}
                  onChange={(_, value) => field.onChange(value)}
                  color='primary'
                />
              }
              label={field.value ? t('active') : t('inactive')}
            />
          )}
        />

        <div className='flex flex-col gap-2'>
          <Typography variant='body2'>{t('imageUrl')}</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='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'>
                    {t('uploadImage')}
                  </Typography>
                </label>
                <input
                  id='upload-image'
                  type='file'
                  accept='image/*'
                  className='hidden'
                  onChange={async e => {
                    const file = e.target.files?.[0] ?? null
                    if (!file) {
                      setValue('image', null)
                      return
                    }

                    const processed = await promptAndProcessImage(file)
                    if (!processed) {
                      setValue('image', null)
                      return
                    }

                    setValue('image', processed, { shouldDirty: true })
                  }}
                />
              </>
            ) : (
              <div className='relative w-full flex flex-col items-center'>
                <img
                  src={
                    typeof imageValue === 'string' ? getImageUrl(imageValue) : URL.createObjectURL(imageValue as File)
                  }
                  alt='Preview'
                  className='w-full h-48 object-cover rounded-lg shadow-sm'
                />
                <Button
                  variant='outlined'
                  color='error'
                  size='small'
                  onClick={() => setValue('image', null, { shouldDirty: true })}
                  className='mt-2'
                >
                  {t('removeImage')}
                </Button>
              </div>
            )}
          </div>
        </div>

        <div className='flex justify-end gap-3 mt-4'>
          <Button variant='tonal' color='secondary' onClick={handleClose}>
            {t('cancel')}
          </Button>
          <Button
            variant='contained'
            type='submit'
            disabled={addCategory.isPending}
            isLoading={addCategory.isPending}
          >
            {addCategory.isPending ? `${t('save')}...` : t('save')}
          </Button>
        </div>
      </form>
    </Drawer>
  )
}

export default AddCategoryDrawer
