'use client'

import { useParams, useRouter } from 'next/navigation'
import { useForm, Controller } from 'react-hook-form'
import { useEffect, useMemo } from 'react'
import { Button, Card, Divider, Typography } from '@mui/material'
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 { getImageUrl } from '@/utils'
import { useGetProduct, useUpdateProduct, useUpdateProductImage } from '@/@core/hooks/data/products'
import { useTranslations } from 'next-intl'
import { useGetCategoriesDropdown } from '@/@core/hooks/data/categories'
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
}

export default function EditProductPage() {
  const t = useTranslations('editProduct')
  const productsT = useTranslations('PRODUCTS')
  const { id } = useParams()
  const router = useRouter()

  const { data: productData, isLoading } = useGetProduct(id as string)
  const updateProduct = useUpdateProduct()
  const updateImage = useUpdateProductImage()
  const {
    control,
    handleSubmit,
    reset,
    formState: { errors }
  } = useForm<any>()
  const { data: categoriesDropdown, isLoading: categoriesLoading } = useGetCategoriesDropdown({
    sort_by: 'sort_order',
    sort_as: 'asc'
  })

  const categoryOptions = useMemo<CategoryOption[]>(() => {
    if (!Array.isArray(categoriesDropdown)) {
      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(categoriesDropdown)
  }, [categoriesDropdown])

  useEffect(() => {
    const values = productData?.data
    if (values) {
      const normalizedValues = {
        ...values,
        category_id: values.category_id ?? values.category?.id ?? ''
      }
      reset(normalizedValues)
    }
  }, [productData, reset])

  const onSubmit = async (values: any) => {
    try {
      await updateProduct.mutateAsync({
        id: id as string,
        payload: {
          ...values,
          category_id: values?.category_id ? values?.category_id : undefined
        }
      })
      router.push('/products')
    } catch (error) {
      console.error('Error updating product:', error)
    }
  }

  const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!id || !e.target.files?.[0]) return
    const file = e.target.files[0]
    const processed = await promptAndProcessImage(file)
    if (!processed) {
      return
    }

    try {
      await updateImage.mutateAsync({ id: id as string, payload: { image: processed } })
    } catch (error) {
      console.error('Error updating product image:', error)
    }
  }

  if (isLoading) return <Typography>{t('loading')}</Typography>

  const product = productData?.data

  return (
    <div className='p-6'>
      <Card className='p-6 space-y-4'>
        <Typography variant='h5'>{t('title')}</Typography>
        <Divider />

        <div className='flex flex-col gap-2 mb-4'>
          <Typography variant='body2'>{t('imageSection')}</Typography>

          <div className='flex flex-col items-center justify-center border-2 border-solid border-gray-200 rounded-xl p-4 hover:border-blue-300 transition-colors md:w-[50%] w-full'>
            {product?.image ? (
              <div className='relative w-full flex flex-col items-center'>
                <img
                  src={getImageUrl(product.image as any)}
                  alt='Product'
                  className='w-full md:w-[50%] h-48 object-contain rounded-lg'
                />

                <div className='flex gap-2 mt-3'>
                  <Button variant='outlined' component='label'>
                    {t('changeImage')}
                    <input type='file' accept='image/*' hidden onChange={handleImageChange} />
                  </Button>
                </div>
              </div>
            ) : (
              <>
                <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('uploadNew')}
                  </Typography>
                </label>
                <input id='upload-image' type='file' accept='image/*' className='hidden' onChange={handleImageChange} />
              </>
            )}
          </div>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className='flex flex-col gap-4'>
          <div className='flex flex-col md:flex-row justify-between gap-4'>
            {' '}
            <Controller
              name='name_ar'
              control={control}
              render={({ field }) => <CustomTextField {...field} label={t('nameAr')} fullWidth />}
            />
            <Controller
              name='name_en'
              control={control}
              render={({ field }) => <CustomTextField {...field} label={t('nameEn')} fullWidth />}
            />
          </div>
          <div className='flex flex-col md:flex-row justify-between gap-4'>
            <Controller
              name='price'
              control={control}
              render={({ field }) => <CustomTextField {...field} label={t('price')} type='number' fullWidth />}
            />

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

          <Controller
            name='category_id'
            control={control}
            render={({ field: { value, onChange, onBlur, ref } }) => {
              const selectedOption = categoryOptions?.find(option => option.id === String(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={productsT('loading')}
                  noOptionsText={productsT('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 ? productsT('category') : `${productsT('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={productsT('category')}
                      placeholder={productsT('category')}
                      fullWidth
                      error={!!errors.category_id}
                      helperText={errors.category_id?.message as string}
                    />
                  )}
                />
              )
            }}
          />

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

          <div className='flex flex-col md:flex-row justify-between gap-4'>
            <Controller
              name='description_ar'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('descriptionAr')} multiline rows={2} fullWidth />
              )}
            />

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

          <div className='flex gap-3 justify-end mt-4'>
            <Button variant='outlined' color='secondary' onClick={() => router.back()}>
              {t('cancel')}
            </Button>
            <Button type='submit' variant='contained' color='primary' disabled={updateProduct.isPending}>
              {updateProduct.isPending ? t('saving') : t('saveChanges')}
            </Button>
          </div>
        </form>
      </Card>
    </div>
  )
}
