'use client'

import { useTranslations } from 'next-intl'
import { useRouter } from 'next/navigation'
import { Controller, useForm } from 'react-hook-form'
import { useMemo } from 'react'
import Card from '@mui/material/Card'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Button from '@mui/material/Button'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete'
import Box from '@mui/material/Box'
import Chip from '@mui/material/Chip'
import CustomTextField from '@core/components/mui/TextField'
import { useAddProduct } from '@/@core/hooks/data/products'
import { useGetCategoriesDropdown } from '@/@core/hooks/data/categories/useGetCategoriesDropdown'
import { ICategory } from '@/types/data/categories/category.interface'
import { promptAndProcessImage } from '@/utils/imageCompression'

type CategoryOption = {
  id: string
  depth: number
  hasChildren: boolean
  nameEn: string
  nameAr: string
  parentNameEn?: string | null
}

const baseCategoryFilter = createFilterOptions<CategoryOption>({
  matchFrom: 'any',
  stringify: option => `${option.nameEn} ${option.nameAr}`
})

const filterCategoryOptions = (options: CategoryOption[], params: Parameters<typeof baseCategoryFilter>[1]) => {
  const filtered = baseCategoryFilter(options, params)

  if (!params.inputValue) {
    return filtered.slice(0, 200)
  }

  return filtered
}

const AddProductPage = () => {
  const t = useTranslations('PRODUCTS')
  const validationT = useTranslations('VALIDATION')
  const router = useRouter()
  const addProduct = useAddProduct()

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors }
  } = useForm<any>({
    defaultValues: {
      category_id: '',
      sku: '',
      name_ar: '',
      name_en: '',
      description_ar: '',
      description_en: '',
      price: '',
      discount_price: '',
      preparation_time: '',
      calories: '',
      sort_order: 1,
      is_featured: false,
      is_available: true,
      image: undefined,
      images: []
    }
  })

  const handleFormSubmit = async (values: any) => {
    try {
      const dto: any = {
        ...values,
        preparation_time: Number(values.preparation_time),
        calories: Number(values.calories),
        price: String(values.price),
        discount_price: values.discount_price ? String(values.discount_price) : undefined,
        image: values.image instanceof FileList ? values.image[0] : values.image,
        images: values.images instanceof FileList ? Array.from(values.images as any) : (values.images as File[]),
        is_featured: values.is_featured ? 1 : 0,
        is_available: values.is_available ? 1 : 0
      }

      await addProduct.mutateAsync(dto)
      reset()
      router.push('/products')
    } catch (error) {
      console.error('Error adding product:', error)
    }
  }

  const { data: categoriesData, isLoading: categoriesLoading } = useGetCategoriesDropdown()

  const categoryOptions = useMemo<CategoryOption[]>(() => {
    if (!Array.isArray(categoriesData)) {
      return []
    }

    const flatten = (
      categories: ICategory[],
      depth = 0,
      parent?: { nameEn: string; nameAr: string }
    ): CategoryOption[] =>
      categories.flatMap(category => {
        const hasChildren = Array.isArray(category?.children) && category?.children?.length > 0
        const current: CategoryOption = {
          id: String(category?.id),
          depth,
          hasChildren,
          nameEn: category?.name_en,
          nameAr: category?.name_ar,
          parentNameEn: parent?.nameEn ?? null
        }
        const children =
          Array.isArray(category?.children) && category?.children?.length > 0
            ? flatten(category?.children, depth + 1, { nameEn: category?.name_en, nameAr: category?.name_ar })
            : []

        return [current, ...children]
      })

    return flatten(categoriesData)
  }, [categoriesData])

  return (
    <div className='p-6'>
      <Card className='p-6 space-y-6'>
        <div className='flex items-center justify-between'>
          <Typography variant='h5'>{t('addProduct')}</Typography>
          <Button variant='outlined' color='secondary' onClick={() => router.push('/products')}>
            {t('backToList')}
          </Button>
        </div>

        <Divider />

        <form onSubmit={handleSubmit(handleFormSubmit)} className='flex flex-col gap-5'>
          <div className='grid md:grid-cols-2 gap-4'>
            <Controller
              name='category_id'
              control={control}
              rules={{ required: validationT('REQUIRED_CATEGORY') }}
              render={({ field: { value, onChange, onBlur, ref } }) => {
                const selectedOption = categoryOptions.find(option => option.id === value) ?? null

                return (
                  <Autocomplete
                    value={selectedOption}
                    options={categoryOptions}
                    loading={categoriesLoading}
                    filterOptions={filterCategoryOptions}
                    isOptionEqualToValue={(option, optionValue) => option.id === optionValue.id}
                    getOptionLabel={option => option.nameEn}
                    onChange={(_, newValue) => onChange(newValue?.id ?? '')}
                    onBlur={onBlur}
                    loadingText={t('loading')}
                    noOptionsText={t('noData')}
                    ListboxProps={{ style: { maxHeight: 360 } }}
                    renderOption={(props, option) => {
                      const isMainCategory = option.depth === 0

                      return (
                        <li {...props}>
                          <Box
                            sx={{
                              width: '100%',
                              px: 1.5,
                              py: 1,
                              borderRadius: 1,
                              bgcolor: isMainCategory ? 'action.selected' : 'background.paper',
                              boxShadow: isMainCategory ? 1 : 0,
                              ml: isMainCategory ? 0 : option.depth * 2,
                              borderLeft: isMainCategory ? 'none' : '2px solid',
                              borderColor: isMainCategory ? 'transparent' : 'primary.main',
                              display: 'flex',
                              flexDirection: 'column',
                              gap: 0.5
                            }}
                          >
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Chip
                                size='small'
                                color={isMainCategory ? 'primary' : 'default'}
                                variant={isMainCategory ? 'filled' : 'outlined'}
                                label={isMainCategory ? t('category') : `${t('category')} - L${option.depth}`}
                              />
                              <Typography variant='body2' sx={{ fontWeight: isMainCategory ? 600 : 500 }}>
                                {option.nameEn}
                              </Typography>
                            </Box>
                            <Typography variant='caption' color={isMainCategory ? 'text.primary' : 'text.secondary'}>
                              {option.nameAr}
                            </Typography>
                            {!!option.parentNameEn && (
                              <Typography variant='caption' color='text.disabled'>
                                Parent: {option.parentNameEn}
                              </Typography>
                            )}
                          </Box>
                        </li>
                      )
                    }}
                    renderInput={params => (
                      <CustomTextField
                        {...params}
                        inputRef={ref}
                        label={t('category')}
                        placeholder={t('category')}
                        fullWidth
                        error={!!errors.category_id}
                        helperText={errors.category_id?.message as string}
                      />
                    )}
                  />
                )
              }}
            />

            <Controller
              name='sku'
              control={control}
              rules={{ required: 'رمز المنتج مطلوب' }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='رمز المنتج (SKU)'
                  fullWidth
                  error={!!errors.sku}
                  helperText={errors.sku?.message as string}
                />
              )}
            />

            <Controller
              name='name_ar'
              control={control}
              rules={{ required: 'الاسم بالعربية مطلوب' }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='الاسم بالعربية'
                  fullWidth
                  error={!!errors.name_ar}
                  helperText={errors.name_ar?.message as string}
                />
              )}
            />

            <Controller
              name='name_en'
              control={control}
              rules={{ required: 'الاسم بالإنجليزية مطلوب' }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='الاسم بالإنجليزية'
                  fullWidth
                  error={!!errors.name_en}
                  helperText={errors.name_en?.message as string}
                />
              )}
            />

            <Controller
              name='description_ar'
              control={control}
              rules={{ required: 'الوصف بالعربية مطلوب' }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='الوصف بالعربية'
                  multiline
                  rows={2}
                  fullWidth
                  error={!!errors.description_ar}
                  helperText={errors.description_ar?.message as string}
                />
              )}
            />

            <Controller
              name='description_en'
              control={control}
              rules={{ required: 'الوصف بالإنجليزية مطلوب' }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='الوصف بالإنجليزية'
                  multiline
                  rows={2}
                  fullWidth
                  error={!!errors.description_en}
                  helperText={errors.description_en?.message as string}
                />
              )}
            />

            <Controller
              name='price'
              control={control}
              rules={{
                required: 'السعر مطلوب',
                min: { value: 1, message: 'يجب أن يكون السعر أكبر من صفر' }
              }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='السعر'
                  type='number'
                  error={!!errors.price}
                  helperText={errors.price?.message as string}
                />
              )}
            />

            <Controller
              name='discount_price'
              control={control}
              rules={{
                validate: value => !value || Number(value) >= 0 || 'يجب ألا يكون السعر أقل من صفر'
              }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='سعر الخصم'
                  type='number'
                  error={!!errors.discount_price}
                  helperText={errors.discount_price?.message as string}
                />
              )}
            />

            <Controller
              name='preparation_time'
              control={control}
              rules={{
                required: 'وقت التحضير مطلوب',
                min: { value: 1, message: 'يجب أن يكون أكبر من صفر' }
              }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='وقت التحضير (دقيقة)'
                  type='number'
                  error={!!errors.preparation_time}
                  helperText={errors.preparation_time?.message as string}
                />
              )}
            />

            {/* 🔥 السعرات */}
            <Controller
              name='calories'
              control={control}
              rules={{
                required: 'عدد السعرات مطلوب',
                min: { value: 1, message: 'يجب أن يكون أكبر من صفر' }
              }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='السعرات الحرارية'
                  type='number'
                  error={!!errors.calories}
                  helperText={errors.calories?.message as string}
                />
              )}
            />

            <Controller
              name='sort_order'
              control={control}
              rules={{
                required: 'ترتيب العرض مطلوب',
                min: { value: 1, message: 'يجب أن يكون أكبر من صفر' }
              }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  label='ترتيب العرض'
                  type='number'
                  error={!!errors.sort_order}
                  helperText={errors.sort_order?.message as string}
                />
              )}
            />
          </div>

          <div className='flex flex-wrap gap-6'>
            <Controller
              name='is_featured'
              control={control}
              render={({ field }) => (
                <FormControlLabel
                  control={<Switch checked={field.value} onChange={(_, val) => field.onChange(val)} color='primary' />}
                  label={field.value ? 'مميز' : 'غير مميز'}
                />
              )}
            />

            <Controller
              name='is_available'
              control={control}
              render={({ field }) => (
                <FormControlLabel
                  control={<Switch checked={field.value} onChange={(_, val) => field.onChange(val)} color='primary' />}
                  label={field.value ? 'متوفر' : 'غير متوفر'}
                />
              )}
            />
          </div>

          <Controller
            name='image'
            control={control}
            rules={{ required: 'الصورة الرئيسية مطلوبة' }}
            render={({ field }) => (
              <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 md:w-[50%]'>
                  {!watch('image') ? (
                    <>
                      <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'>
                          رفع صورة
                        </Typography>
                      </label>
                      <input
                        id='upload-image'
                        type='file'
                        accept='image/*'
                        className='hidden'
                        onChange={async e => {
                          const file = e.target.files?.[0]
                          if (!file) {
                            setValue('image', undefined, { shouldValidate: true })
                            return
                          }

                          const processed = await promptAndProcessImage(file)
                          if (!processed) {
                            setValue('image', undefined, { shouldValidate: true })
                            return
                          }

                          setValue('image', processed, { shouldValidate: true })
                        }}
                      />
                    </>
                  ) : (
                    <div className='relative w-full h-auto flex flex-col items-center'>
                      <img
                        src={URL.createObjectURL(watch('image') as File)}
                        alt='Preview'
                        className='w-full h-[250px] object-contain rounded-lg'
                      />
                      <Button
                        variant='outlined'
                        color='error'
                        size='small'
                        onClick={() => setValue('image', undefined, { shouldValidate: true })}
                        className='mt-2'
                      >
                        إزالة الصورة
                      </Button>
                    </div>
                  )}
                </div>

                {errors.image && (
                  <Typography color='error' variant='caption'>
                    {errors.image.message as string}
                  </Typography>
                )}
              </div>
            )}
          />
          <Controller
            name='images'
            control={control}
            rules={{
              validate: value => !value || value.length <= 5 || 'يمكن رفع حتى 5 صور فقط'
            }}
            render={({ field }) => (
              <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'>
                  {watch('images')?.length === 0 ? (
                    <>
                      <label htmlFor='upload-images' 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='upload-images'
                        type='file'
                        multiple
                        accept='image/*'
                        className='hidden'
                        onChange={async e => {
                          const files = Array.from(e.target.files || [])
                          if (!files.length) {
                            setValue('images', [], { shouldValidate: true })
                            return
                          }

                          const processedFiles: File[] = []

                          for (const f of files) {
                            const processed = await promptAndProcessImage(f)
                            if (processed) {
                              processedFiles.push(processed)
                            }
                          }

                          setValue('images', processedFiles, { shouldValidate: true })
                        }}
                      />
                    </>
                  ) : (
                    <div className='w-full grid grid-cols-2 gap-2'>
                      {watch('images')?.map((file: any, index: any) => (
                        <div key={index} className='relative'>
                          <img
                            src={URL.createObjectURL(file)}
                            alt={`Extra-${index}`}
                            className='w-full h-[250px] object-contain rounded-md shadow-sm'
                          />
                        </div>
                      ))}
                      <Button
                        variant='outlined'
                        color='error'
                        size='small'
                        onClick={() => setValue('images', [], { shouldValidate: true })}
                        className='col-span-2 mt-2'
                      >
                        إزالة الكل
                      </Button>
                    </div>
                  )}
                </div>
                {errors.images && (
                  <Typography color='error' variant='caption'>
                    {errors.images.message as string}
                  </Typography>
                )}
              </div>
            )}
          />

          <div className='flex justify-end gap-3 mt-4'>
            <Button variant='outlined' color='secondary' onClick={() => router.push('/dashboard/products')}>
              إلغاء
            </Button>
            <Button variant='contained' type='submit' disabled={addProduct.isPending}>
              {addProduct.isPending ? 'جاري الحفظ...' : 'حفظ المنتج'}
            </Button>
          </div>
        </form>
      </Card>
    </div>
  )
}

export default AddProductPage
