'use client'

import { useMutation, useQuery } from '@apollo/client'
import { X, Star, Upload, RefreshCw } from 'lucide-react'
import Image from 'next/image'
import { useState, useRef, useEffect, useCallback } from 'react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { CREATE_PRODUCT, UPDATE_PRODUCT, CHECK_ARTICLE_UNIQUENESS } from '@/graphql/mutations'
import { GET_CATEGORIES } from '@/graphql/queries'

interface Product {
  id: string
  name: string
  article: string
  description: string
  price: number
  pricePerSet?: number
  quantity: number
  setQuantity?: number
  ordered?: number
  inTransit?: number
  stock?: number
  sold?: number
  type: 'PRODUCT' | 'CONSUMABLE'
  category: { id: string; name: string } | null
  brand: string
  color: string
  size: string
  weight: number
  dimensions: string
  material: string
  images: string[]
  mainImage: string
  isActive: boolean
  organization?: { id: string; market?: string }
}

interface ProductFormProps {
  product?: Product | null
  onSave: () => void
  onCancel: () => void
}


export function ProductForm({ product, onSave, onCancel }: ProductFormProps) {
  const [formData, setFormData] = useState({
    name: product?.name || '',
    article: product?.article || '',
    autoGenerateArticle: !product?.article, // Автогенерация только для новых товаров
    description: product?.description || '',
    price: product?.price || 0,
    quantity: product?.quantity || 0,
    setQuantity: product?.setQuantity || 0, // Количество комплектов
    pricePerSet: product?.pricePerSet || 0, // Цена за комплект
    ordered: product?.ordered || 0, // Заказано
    inTransit: product?.inTransit || 0, // В пути
    stock: product?.stock || 0, // Остаток
    sold: product?.sold || 0, // Продано
    type: product?.type || ('PRODUCT' as 'PRODUCT' | 'CONSUMABLE'),
    categoryId: product?.category?.id || 'none',
    brand: product?.brand || '',
    color: product?.color || '',
    size: product?.size || '',
    weight: product?.weight || 0,
    dimensions: product?.dimensions || '',
    material: product?.material || '',
    images: product?.images || [],
    mainImage: product?.mainImage || '',
    isActive: product?.isActive ?? true,
  })

  const [isUploading] = useState(false)
  const [uploadingImages, setUploadingImages] = useState<Set<number>>(new Set())
  const [articleValidation, setArticleValidation] = useState<{
    isChecking: boolean
    isValid: boolean
    message: string
  }>({
    isChecking: false,
    isValid: true,
    message: '',
  })
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [createProduct, { loading: creating }] = useMutation(CREATE_PRODUCT)
  const [updateProduct, { loading: updating }] = useMutation(UPDATE_PRODUCT)
  const [checkArticleUniqueness] = useMutation(CHECK_ARTICLE_UNIQUENESS)

  // Загружаем категории
  const { data: categoriesData } = useQuery(GET_CATEGORIES)

  const loading = creating || updating

  // Генерация артикула СФ
  const generateArticle = () => {
    const prefix = formData.type === 'PRODUCT' ? 'SF-T' : 'SF-C' // T=Товар, C=Расходник
    const timestamp = Date.now().toString().slice(-6) // Последние 6 цифр timestamp
    const random = Math.floor(Math.random() * 1000)
      .toString()
      .padStart(3, '0')
    return `${prefix}-${timestamp}-${random}`
  }

  // Автогенерация артикула при смене типа
  useEffect(() => {
    if (formData.autoGenerateArticle && formData.type) {
      setFormData((prev) => ({
        ...prev,
        article: generateArticle(),
      }))
    }
  }, [formData.type, formData.autoGenerateArticle])

  const handleInputChange = (field: string, value: string | number | boolean) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }))
  }

  const handleGenerateNewArticle = () => {
    setFormData((prev) => ({
      ...prev,
      article: generateArticle(),
    }))
  }

  // Функция проверки уникальности артикула
  const checkArticleUniquenessFn = useCallback(
    async (article: string) => {
      if (!article || article.length < 3) {
        setArticleValidation({ isChecking: false, isValid: true, message: '' })
        return
      }

      setArticleValidation({ isChecking: true, isValid: true, message: '' })

      try {
        const result = await checkArticleUniqueness({
          variables: {
            article,
            excludeId: product?.id || null,
          },
        })

        // Безопасная проверка наличия данных
        if (!result?.data?.checkArticleUniqueness) {
          setArticleValidation({
            isChecking: false,
            isValid: true,
            message: '',
          })
          return
        }

        const { isUnique, existingProduct } = result.data.checkArticleUniqueness

        if (isUnique) {
          setArticleValidation({
            isChecking: false,
            isValid: true,
            message: '✅ Артикул доступен',
          })
        } else {
          setArticleValidation({
            isChecking: false,
            isValid: false,
            message: `❌ Артикул уже используется товаром "${existingProduct?.name || 'неизвестным'}"`,
          })
        }
      } catch (error) {
        console.error('Error checking article uniqueness:', error)
        setArticleValidation({
          isChecking: false,
          isValid: true,
          message: '',
        })
      }
    },
    [checkArticleUniqueness, product?.id],
  )

  // Debounced проверка артикула
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (formData.article && !formData.autoGenerateArticle && formData.article.length >= 3) {
        // Проверяем только если артикул изменился по сравнению с оригинальным
        if (!product || formData.article !== product.article) {
          checkArticleUniquenessFn(formData.article)
        } else {
          // Если артикул не изменился при редактировании - валидация успешна
          setArticleValidation({
            isChecking: false,
            isValid: true,
            message: '✅ Текущий артикул товара',
          })
        }
      } else if (formData.article.length < 3) {
        // Сбрасываем валидацию если артикул слишком короткий
        setArticleValidation({ isChecking: false, isValid: true, message: '' })
      }
    }, 500)

    return () => clearTimeout(timeoutId)
  }, [formData.article, formData.autoGenerateArticle, product, checkArticleUniquenessFn])

  const handleImageUpload = async (files: FileList) => {
    const newUploadingIndexes = new Set<number>()
    const startIndex = formData.images.length

    // Добавляем плейсхолдеры для загружаемых изображений
    const placeholders = Array.from(files).map((_, index) => {
      newUploadingIndexes.add(startIndex + index)
      return '' // Пустой URL как плейсхолдер
    })

    setUploadingImages((prev) => new Set([...prev, ...newUploadingIndexes]))
    setFormData((prev) => ({
      ...prev,
      images: [...prev.images, ...placeholders],
    }))

    try {
      // Загружаем каждое изображение
      const uploadPromises = Array.from(files).map(async (file, index) => {
        const actualIndex = startIndex + index
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 'product')

        const response = await fetch('/api/upload-file', {
          method: 'POST',
          body: formData,
        })

        if (!response.ok) {
          throw new Error('Ошибка загрузки изображения')
        }

        const result = await response.json()
        return { index: actualIndex, url: result.fileUrl }
      })

      const results = await Promise.all(uploadPromises)

      // Обновляем URLs загруженных изображений
      setFormData((prev) => {
        const newImages = [...prev.images]
        results.forEach(({ index, url }) => {
          newImages[index] = url
        })
        return {
          ...prev,
          images: newImages,
          mainImage: prev.mainImage || results[0]?.url || '', // Устанавливаем первое изображение как главное
        }
      })

      toast.success('Изображения успешно загружены')
    } catch (error) {
      console.error('Error uploading images:', error)
      toast.error('Ошибка загрузки изображений')

      // Удаляем неудачные плейсхолдеры
      setFormData((prev) => ({
        ...prev,
        images: prev.images.slice(0, startIndex),
      }))
    } finally {
      // Убираем индикаторы загрузки
      setUploadingImages((prev) => {
        const updated = new Set(prev)
        newUploadingIndexes.forEach((index) => updated.delete(index))
        return updated
      })
    }
  }

  const handleRemoveImage = (indexToRemove: number) => {
    setFormData((prev) => {
      const newImages = prev.images.filter((_, index) => index !== indexToRemove)
      const removedImageUrl = prev.images[indexToRemove]

      return {
        ...prev,
        images: newImages,
        mainImage: prev.mainImage === removedImageUrl ? newImages[0] || '' : prev.mainImage,
      }
    })
  }

  const handleSetMainImage = (imageUrl: string) => {
    setFormData((prev) => ({
      ...prev,
      mainImage: imageUrl,
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!formData.name || !formData.article || formData.price <= 0) {
      toast.error('Пожалуйста, заполните все обязательные поля')
      return
    }

    // Проверяем уникальность артикула
    if (!articleValidation.isValid) {
      toast.error('Артикул уже используется другим товаром')
      return
    }

    console.warn('📝 ФОРМА ДАННЫЕ ПЕРЕД ОТПРАВКОЙ:', formData)

    try {
      const input = {
        name: formData.name,
        article: formData.article,
        description: formData.description || undefined,
        price: formData.price,
        pricePerSet: formData.pricePerSet || undefined,
        quantity: formData.quantity,
        setQuantity: formData.setQuantity || undefined,
        ordered: formData.ordered || undefined,
        inTransit: formData.inTransit || undefined,
        stock: formData.stock || undefined,
        sold: formData.sold || undefined,
        type: formData.type,
        categoryId: formData.categoryId && formData.categoryId !== 'none' ? formData.categoryId : undefined,
        brand: formData.brand || undefined,
        color: formData.color || undefined,
        size: formData.size || undefined,
        weight: formData.weight || undefined,
        dimensions: formData.dimensions || undefined,
        material: formData.material || undefined,
        images: formData.images.filter((img) => img), // Убираем пустые строки
        mainImage: formData.mainImage || undefined,
        isActive: formData.isActive,
      }

      if (product) {
        console.warn('📝 ОБНОВЛЕНИЕ ТОВАРА - ОТПРАВКА ЗАПРОСА:', input)
        const result = await updateProduct({
          variables: { id: product.id, input },
          refetchQueries: ['GetMyProducts'],
        })
        console.warn('📝 РЕЗУЛЬТАТ ОБНОВЛЕНИЯ ТОВАРА:', result)
        toast.success('Товар успешно обновлен')
      } else {
        console.warn('📝 СОЗДАНИЕ ТОВАРА - ОТПРАВКА ЗАПРОСА:', input)
        const result = await createProduct({
          variables: { input },
          refetchQueries: ['GetMyProducts'],
        })
        console.warn('📝 РЕЗУЛЬТАТ СОЗДАНИЯ ТОВАРА:', result)
        toast.success('Товар успешно создан')
      }

      onSave()
    } catch (error: unknown) {
      console.error('Error saving product:', error)
      toast.error((error as Error).message || 'Ошибка при сохранении товара')
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      {/* Верхняя часть - 2 колонки */}
      <div className="grid grid-cols-2 gap-4">
        {/* Левая колонка */}
        <div className="space-y-3">
          {/* Основная информация */}
          <Card className="bg-white/5 backdrop-blur border-white/10 p-3">
            <h3 className="text-white font-medium mb-3 text-sm">Основная информация</h3>
            <div className="space-y-3">
              <div>
                <Label className="text-white/80 text-xs mb-1 block">
                  Название товара <span className="text-red-400">*</span>
                </Label>
                <Input
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  placeholder="iPhone 15 Pro Max"
                  className="glass-input text-white placeholder:text-white/40 h-8 text-sm"
                  required
                />
              </div>

              <div>
                <Label className="text-white/80 text-xs mb-1 block">
                  Артикул СФ <span className="text-red-400">*</span>
                </Label>
                <div className="flex gap-2">
                  <Input
                    value={formData.article}
                    onChange={(e) => {
                      handleInputChange('article', e.target.value)
                      handleInputChange('autoGenerateArticle', false)
                    }}
                    placeholder="SF-T-123456-001"
                    className="glass-input text-white placeholder:text-white/40 h-8 text-sm flex-1"
                    required
                    readOnly={formData.autoGenerateArticle}
                  />
                  {!product && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={handleGenerateNewArticle}
                      className="glass-secondary text-white hover:text-white px-2 h-8"
                      title="Генерировать новый артикул"
                    >
                      <RefreshCw className="h-3 w-3" />
                    </Button>
                  )}
                </div>
                {formData.autoGenerateArticle ? (
                  <p className="text-white/60 text-xs mt-1">Автогенерация</p>
                ) : (
                  <div className="mt-1">
                    {articleValidation.isChecking ? (
                      <p className="text-blue-400 text-xs">🔄 Проверка уникальности...</p>
                    ) : articleValidation.message ? (
                      <p className={`text-xs ${articleValidation.isValid ? 'text-green-400' : 'text-red-400'}`}>
                        {articleValidation.message}
                      </p>
                    ) : null}
                  </div>
                )}
              </div>

              <div className="flex gap-2 relative">
                <div className="flex-1">
                  <Label className="text-white/80 text-xs mb-1 block">
                    Тип <span className="text-red-400">*</span>
                  </Label>
                  <div className="flex border border-white/10 rounded-lg overflow-hidden h-8">
                    <Button
                      type="button"
                      onClick={() => handleInputChange('type', 'PRODUCT')}
                      className={`flex-1 h-full rounded-none text-xs border-0 ${
                        formData.type === 'PRODUCT'
                          ? 'bg-blue-500/20 text-blue-300 hover:bg-blue-500/30'
                          : 'bg-transparent text-white/70 hover:text-white hover:bg-white/5'
                      }`}
                    >
                      Товар
                    </Button>
                    <Button
                      type="button"
                      onClick={() => handleInputChange('type', 'CONSUMABLE')}
                      className={`flex-1 h-full rounded-none border-l border-white/10 text-xs border-t-0 border-r-0 border-b-0 ${
                        formData.type === 'CONSUMABLE'
                          ? 'bg-orange-500/20 text-orange-300 hover:bg-orange-500/30'
                          : 'bg-transparent text-white/70 hover:text-white hover:bg-white/5'
                      }`}
                    >
                      Расходник
                    </Button>
                  </div>
                </div>

                <div className="flex-1">
                  <Label className="text-white/80 text-xs mb-1 block">Категория</Label>
                  <Select value={formData.categoryId} onValueChange={(value) => handleInputChange('categoryId', value)}>
                    <SelectTrigger className="glass-input text-white h-8 text-sm">
                      <SelectValue placeholder="Категория" />
                    </SelectTrigger>
                    <SelectContent className="glass-card" side="bottom" align="end">
                      <SelectItem value="none">Без категории</SelectItem>
                      {categoriesData?.categories?.map((category: { id: string; name: string }) => (
                        <SelectItem key={category.id} value={category.id} className="text-white">
                          {category.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div>
                <Label className="text-white/80 text-xs mb-1 block">Описание</Label>
                <textarea
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="Описание товара..."
                  className="glass-input text-white placeholder:text-white/40 w-full resize-none text-sm h-16"
                  style={{
                    background: 'rgba(255, 255, 255, 0.05)',
                    border: '1px solid rgba(255, 255, 255, 0.1)',
                    borderRadius: '0.5rem',
                    padding: '0.5rem',
                  }}
                />
              </div>
            </div>
          </Card>

          {/* Ценообразование */}
          <Card className="bg-white/5 backdrop-blur border-white/10 p-3">
            <h3 className="text-white font-medium mb-3 text-sm">Ценообразование</h3>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Кол-во предметов</Label>
                <Input
                  type="number"
                  value={formData.quantity || ''}
                  onChange={(e) => handleInputChange('quantity', parseInt(e.target.value) || 0)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">
                  Цена за ед. (₽) <span className="text-red-400">*</span>
                </Label>
                <Input
                  type="number"
                  step="0.01"
                  value={formData.price || ''}
                  onChange={(e) => handleInputChange('price', parseFloat(e.target.value) || 0)}
                  className="glass-input text-white h-8 text-sm"
                  required
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Кол-во комплектов</Label>
                <Input
                  type="number"
                  value={formData.setQuantity || ''}
                  onChange={(e) => handleInputChange('setQuantity', parseInt(e.target.value) || 0)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Цена за компл. (₽)</Label>
                <Input
                  type="number"
                  step="0.01"
                  value={formData.pricePerSet || ''}
                  onChange={(e) => handleInputChange('pricePerSet', parseFloat(e.target.value) || 0)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
            </div>
          </Card>
        </div>

        {/* Правая колонка */}
        <div className="space-y-3">
          {/* Характеристики */}
          <Card className="bg-white/5 backdrop-blur border-white/10 p-3">
            <h3 className="text-white font-medium mb-3 text-sm">Характеристики</h3>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Бренд</Label>
                <Input
                  value={formData.brand}
                  onChange={(e) => handleInputChange('brand', e.target.value)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Цвет</Label>
                <Input
                  value={formData.color}
                  onChange={(e) => handleInputChange('color', e.target.value)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Размер</Label>
                <Input
                  value={formData.size}
                  onChange={(e) => handleInputChange('size', e.target.value)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div>
                <Label className="text-white/80 text-xs mb-1 block">Вес (кг)</Label>
                <Input
                  type="number"
                  step="0.001"
                  value={formData.weight || ''}
                  onChange={(e) => handleInputChange('weight', parseFloat(e.target.value) || 0)}
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div className="col-span-2">
                <Label className="text-white/80 text-xs mb-1 block">Габариты</Label>
                <Input
                  value={formData.dimensions}
                  onChange={(e) => handleInputChange('dimensions', e.target.value)}
                  placeholder="159.9 × 76.7 × 8.25 мм"
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
              <div className="col-span-2">
                <Label className="text-white/80 text-xs mb-1 block">Материал</Label>
                <Input
                  value={formData.material}
                  onChange={(e) => handleInputChange('material', e.target.value)}
                  placeholder="Титан, стекло"
                  className="glass-input text-white h-8 text-sm"
                />
              </div>
            </div>
          </Card>

          {/* Изображения */}
          <Card className="bg-white/5 backdrop-blur border-white/10 p-3">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-white font-medium text-sm">Изображения</h3>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                multiple
                onChange={(e) => e.target.files && handleImageUpload(e.target.files)}
                className="hidden"
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploading}
                className="glass-secondary text-white hover:text-white h-7 px-2 text-xs"
              >
                <Upload className="h-3 w-3 mr-1" />
                Загрузить
              </Button>
            </div>

            {formData.images.length > 0 && (
              <div className="grid grid-cols-4 gap-2">
                {formData.images.slice(0, 8).map((imageUrl, index) => (
                  <div key={index} className="relative group">
                    {uploadingImages.has(index) ? (
                      <div className="aspect-square bg-white/10 rounded flex items-center justify-center">
                        <div className="animate-spin rounded-full h-4 w-4 border border-white border-t-transparent"></div>
                      </div>
                    ) : imageUrl ? (
                      <>
                        <Image
                          src={imageUrl}
                          alt={`${index + 1}`}
                          width={60}
                          height={60}
                          className="w-full aspect-square object-contain rounded bg-white/5"
                        />
                        {formData.mainImage === imageUrl && (
                          <Star className="absolute top-1 left-1 h-3 w-3 text-yellow-400 fill-current" />
                        )}
                        <div className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
                          {formData.mainImage !== imageUrl && (
                            <Button
                              type="button"
                              size="sm"
                              variant="outline"
                              onClick={() => handleSetMainImage(imageUrl)}
                              className="p-0 h-4 w-4 bg-white/20 border-white/30 hover:bg-white/30"
                            >
                              <Star className="h-2 w-2 text-white" />
                            </Button>
                          )}
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            onClick={() => handleRemoveImage(index)}
                            className="p-0 h-4 w-4 bg-red-500/20 border-red-400/30 hover:bg-red-500/30"
                          >
                            <X className="h-2 w-2 text-white" />
                          </Button>
                        </div>
                      </>
                    ) : (
                      <div className="aspect-square bg-white/10 rounded flex items-center justify-center">
                        <div className="text-white/40 text-xs">Нет</div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </Card>
        </div>
      </div>

      {/* Кнопки управления */}
      <div className="flex gap-3 pt-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          className="flex-1 border-purple-400/30 text-purple-200 hover:bg-purple-500/10 hover:border-purple-300 transition-all duration-300 h-9"
        >
          Отмена
        </Button>
        <Button
          type="submit"
          disabled={loading || isUploading}
          className="flex-1 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white border-0 shadow-lg shadow-purple-500/25 hover:shadow-purple-500/40 transition-all duration-300 h-9"
        >
          {loading ? 'Сохранение...' : product ? 'Сохранить изменения' : 'Создать товар'}
        </Button>
      </div>
    </form>
  )
}
