'use client'

import { useQuery, useMutation } from '@apollo/client'
import { Package, Save, X, Edit, Check } from 'lucide-react'
import Image from 'next/image'
import { useState, useEffect, useMemo } from 'react'
import { toast } from 'sonner'

// Alert dialog no longer needed for supplies
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
// ИСПРАВЛЕНО: Используем новый V2 запрос для расходников фулфилмента
import { GET_MY_FULFILLMENT_CONSUMABLES_V2, UPDATE_FULFILLMENT_CONSUMABLE } from '@/graphql/queries/fulfillment-services-v2'
import { useAuthContext } from '@/contexts/AuthContext'

// ИСПРАВЛЕНО: Интерфейс для V2 расходников фулфилмента
interface FulfillmentConsumable {
  id: string
  fulfillmentId: string
  inventoryId?: string
  name: string
  nameForSeller?: string
  article?: string
  description?: string
  pricePerUnit: number
  unit: string
  minStock: number
  currentStock: number
  isAvailable: boolean
  imageUrl?: string
  sortOrder: number
  createdAt: string
  updatedAt: string
  fulfillment: {
    id: string
    name: string
  }
  inventory?: {
    id: string
    currentStock: number
    product: {
      name: string
    }
  }
}

// ИСПРАВЛЕНО: Интерфейс для редактирования V2 расходников фулфилмента
interface EditableFulfillmentConsumable {
  id: string
  name: string
  nameForSeller: string
  article: string
  description: string
  pricePerUnit: string // Редактируемое поле
  unit: string
  imageUrl: string
  currentStock: number
  minStock: number
  isAvailable: boolean
  isEditing: boolean
  hasChanges: boolean
  inventoryId?: string
}

// PendingChange interface no longer needed

export function SuppliesTab() {
  const { user, isLoading: isCheckingAuth } = useAuthContext()
  const [editableConsumables, setEditableConsumables] = useState<EditableFulfillmentConsumable[]>([])
  const [isSaving, setIsSaving] = useState(false)
  const [isInitialized, setIsInitialized] = useState(false)

  // Debug информация
  console.warn('SuppliesTab - User:', user?.phone, 'Type:', user?.organization?.type, 'User object:', !!user, 'isChecking:', isCheckingAuth)

  // ИСПРАВЛЕНО: Добавляем дополнительную проверку и ждем пока пользователь загрузится
  const shouldSkipQuery = !user || !user.organization || user.organization.type !== 'FULFILLMENT' || isCheckingAuth
  
  // ИСПРАВЛЕНО: Используем V2 GraphQL запросы и мутации
  const { data, loading, error, refetch } = useQuery(GET_MY_FULFILLMENT_CONSUMABLES_V2, {
    skip: shouldSkipQuery,
    fetchPolicy: 'cache-and-network', // Автоматическое обновление данных
    pollInterval: 30000, // Обновление каждые 30 секунд для синхронизации
    errorPolicy: 'all', // Показываем частичные данные при ошибках
  })
  const [updateConsumable] = useMutation(UPDATE_FULFILLMENT_CONSUMABLE)

  // Debug GraphQL запроса
  console.warn('SuppliesTab V2 - Query:', {
    shouldSkipQuery,
    userExists: !!user,
    orgExists: !!user?.organization,
    orgType: user?.organization?.type,
    isCheckingAuth,
    loading,
    error: error?.message,
    dataLength: data?.myFulfillmentConsumables?.length,
  })

  const consumables = data?.myFulfillmentConsumables || []
  
  console.warn('🎯 SuppliesTab render state:', {
    editableConsumablesCount: editableConsumables.length,
    editableConsumables: editableConsumables.map(c => ({ id: c.id, name: c.name, stock: c.currentStock })),
    isInitialized,
    loading,
    error: error?.message,
  })

  // ИСПРАВЛЕНО: Преобразуем загруженные V2 расходники в редактируемый формат
  useEffect(() => {
    console.warn('🔍 useEffect data conversion:', {
      hasData: !!data?.myFulfillmentConsumables,
      dataLength: data?.myFulfillmentConsumables?.length,
      isInitialized,
      firstItem: data?.myFulfillmentConsumables?.[0],
    })
    
    if (data?.myFulfillmentConsumables && !isInitialized) {
      const convertedConsumables: EditableFulfillmentConsumable[] = data.myFulfillmentConsumables.map((consumable: FulfillmentConsumable) => ({
        id: consumable.id,
        name: consumable.name,
        nameForSeller: consumable.nameForSeller || '',
        article: consumable.article || '',
        description: consumable.description || '',
        pricePerUnit: consumable.pricePerUnit ? consumable.pricePerUnit.toString() : '',
        unit: consumable.unit,
        imageUrl: consumable.imageUrl || '',
        currentStock: consumable.inventory?.currentStock || consumable.currentStock,
        minStock: consumable.minStock,
        isAvailable: consumable.isAvailable,
        isEditing: false,
        hasChanges: false,
        inventoryId: consumable.inventoryId,
      }))

      console.warn('✅ Converting data to editableConsumables:', {
        originalCount: data.myFulfillmentConsumables.length,
        convertedCount: convertedConsumables.length,
        convertedItems: convertedConsumables.map(c => ({ 
          id: c.id, 
          name: c.name, 
          article: c.article,
          description: c.description,
          stock: c.currentStock,
          price: c.pricePerUnit,
          unit: c.unit,
          isAvailable: c.isAvailable,
        })),
      })

      setEditableConsumables(convertedConsumables)
      setIsInitialized(true)
    }
  }, [data, isInitialized])

  // Расходники нельзя создавать - они появляются автоматически со склада
  // const addNewRow = () => { ... } - REMOVED

  // Расходники нельзя удалять - они управляются через склад
  // const removeRow = async (supplyId: string, isNew: boolean) => { ... } - REMOVED

  // ИСПРАВЛЕНО: Начать редактирование существующей строки V2
  const startEditing = (consumableId: string) => {
    setEditableConsumables((prev) =>
      prev.map((consumable) => (consumable.id === consumableId ? { ...consumable, isEditing: true } : consumable)),
    )
  }

  // ИСПРАВЛЕНО: Отменить редактирование V2
  const cancelEditing = (consumableId: string) => {
    const consumable = editableConsumables.find((s) => s.id === consumableId)
    if (!consumable) return

    // Возвращаем к исходному состоянию из V2 данных
    const originalConsumable = consumables.find((s: FulfillmentConsumable) => s.id === consumable.id)
    if (originalConsumable) {
      setEditableConsumables((prev) =>
        prev.map((s) =>
          s.id === consumableId
            ? {
                id: originalConsumable.id,
                name: originalConsumable.name,
                nameForSeller: originalConsumable.nameForSeller || '',
                article: originalConsumable.article || '',
                description: originalConsumable.description || '',
                pricePerUnit: originalConsumable.pricePerUnit ? originalConsumable.pricePerUnit.toString() : '',
                unit: originalConsumable.unit,
                imageUrl: originalConsumable.imageUrl || '',
                currentStock: originalConsumable.currentStock,
                minStock: originalConsumable.minStock,
                isAvailable: originalConsumable.isAvailable,
                isEditing: false,
                hasChanges: false,
              }
            : s,
        ),
      )
    }
  }

  // ИСПРАВЛЕНО: Обновить поле V2 (цену и название для селлера можно редактировать)
  const updateField = (consumableId: string, field: keyof EditableFulfillmentConsumable, value: string) => {
    if (field !== 'pricePerUnit' && field !== 'nameForSeller') {
      return // Только цену и название для селлера можно редактировать
    }

    setEditableConsumables((prev) =>
      prev.map((consumable) => {
        if (consumable.id !== consumableId) return consumable

        return {
          ...consumable,
          [field]: value,
          hasChanges: true,
        }
      }),
    )
  }

  // Image upload no longer needed - supplies are readonly except price

  // ИСПРАВЛЕНО: Сохранить все изменения V2 (только цены)
  const saveAllChanges = async () => {
    setIsSaving(true)
    try {
      const consumablesToSave = editableConsumables.filter((s) => s.hasChanges)

      for (const consumable of consumablesToSave) {
        // Проверяем валидность цены (может быть пустой)
        const pricePerUnit = consumable.pricePerUnit.trim() ? parseFloat(consumable.pricePerUnit) : 0

        if (consumable.pricePerUnit.trim() && (pricePerUnit === null || isNaN(pricePerUnit) || pricePerUnit <= 0)) {
          toast.error('Введите корректную цену')
          setIsSaving(false)
          return
        }

        console.warn('🔥 Frontend calling UPDATE_FULFILLMENT_CONSUMABLE V2 with:', {
          id: consumable.id,
          input: { pricePerUnit: pricePerUnit },
          consumableName: consumable.name,
        })

        await updateConsumable({
          variables: { 
            input: {
              id: consumable.id,
              pricePerUnit: pricePerUnit,
              nameForSeller: consumable.nameForSeller,
            },
          },
          refetchQueries: [{ query: GET_MY_FULFILLMENT_CONSUMABLES_V2 }],
        })
      }

      // Сбрасываем флаги изменений
      setEditableConsumables((prev) => prev.map((s) => ({ ...s, hasChanges: false, isEditing: false })))

      toast.success('Изменения успешно сохранены')
    } catch (error) {
      console.error('Error saving changes:', error)
      toast.error('Ошибка при сохранении изменений')
    } finally {
      setIsSaving(false)
    }
  }

  // ИСПРАВЛЕНО: Проверяем есть ли несохраненные изменения V2 (только цены)
  const hasUnsavedChanges = useMemo(() => {
    return editableConsumables.some((s) => s.hasChanges)
  }, [editableConsumables])

  return (
    <div className="h-full flex flex-col">
      <Card className="flex-1 bg-white/5 backdrop-blur border-white/10 p-6 overflow-hidden">
        {/* Заголовок и кнопки */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-lg font-semibold text-white mb-1">Расходники со склада</h2>
            <p className="text-white/70 text-sm">
              Расходники появляются автоматически из поставок. Можно установить цену и название для селлера.
            </p>
          </div>

          <div className="flex gap-3">
            {hasUnsavedChanges && (
              <Button
                onClick={saveAllChanges}
                disabled={isSaving}
                className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white border-0 shadow-lg shadow-green-500/25 hover:shadow-green-500/40 transition-all duration-300 hover:scale-105 disabled:hover:scale-100"
              >
                <Save className="w-4 h-4 mr-2" />
                {isSaving ? 'Сохранение...' : 'Сохранить изменения'}
              </Button>
            )}
          </div>
        </div>

        {/* Таблица расходников */}
        <div className="overflow-auto flex-1">
          {(loading || isCheckingAuth) ? (
            <div className="h-full flex items-center justify-center">
              <div className="text-center">
                <div className="w-16 h-16 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-4 animate-spin">
                  <svg className="w-8 h-8 text-white/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                    />
                  </svg>
                </div>
                <p className="text-white/70 text-sm">
                  {isCheckingAuth ? 'Проверка авторизации...' : 'Загрузка расходников...'}
                </p>
              </div>
            </div>
          ) : error ? (
            <div className="h-full flex items-center justify-center">
              <div className="text-center">
                <div className="w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                  <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                </div>
                <h3 className="text-lg font-semibold text-white mb-2">Ошибка загрузки</h3>
                <p className="text-white/70 text-sm mb-4">
                  Не удалось загрузить расходники
                  {process.env.NODE_ENV === 'development' && (
                    <>
                      <br />
                      <span className="text-xs text-red-300">
                        Debug: {error.message}
                        <br />
                        User type: {user?.organization?.type}
                      </span>
                    </>
                  )}
                </p>
                <Button
                  onClick={() => refetch()}
                  className="bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white"
                >
                  Попробовать снова
                </Button>
              </div>
            </div>
          ) : editableConsumables.length === 0 ? (
            <div className="h-full flex items-center justify-center">
              <div className="text-center">
                <div className="w-16 h-16 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <Package className="w-8 h-8 text-white/50" />
                </div>
                <h3 className="text-lg font-semibold text-white mb-2">Пока нет расходников</h3>
                <p className="text-white/70 text-sm mb-4">Расходники появятся автоматически при получении поставок</p>
              </div>
            </div>
          ) : (
            <div className="bg-white/5 rounded-lg border border-white/10 overflow-hidden">
              <table className="w-full">
                <thead className="bg-white/5">
                  <tr>
                    <th className="text-left p-4 text-white font-medium">№</th>
                    <th className="text-left p-4 text-white font-medium">Фото</th>
                    <th className="text-left p-4 text-white font-medium">Название</th>
                    <th className="text-left p-4 text-white font-medium">Название для селлера</th>
                    <th className="text-left p-4 text-white font-medium">Артикул</th>
                    <th className="text-left p-4 text-white font-medium">Остаток</th>
                    <th className="text-left p-4 text-white font-medium">Единица</th>
                    <th className="text-left p-4 text-white font-medium">Цена за единицу (₽)</th>
                    <th className="text-left p-4 text-white font-medium">Действия</th>
                  </tr>
                </thead>
                <tbody>
                  {(() => {
                    console.warn('🔥 РЕНДЕРИМ ТАБЛИЦУ:', {
                      editableConsumablesLength: editableConsumables.length,
                      items: editableConsumables.map((c, i) => ({ 
                        index: i, 
                        id: c.id, 
                        name: c.name, 
                        article: c.article,
                        description: c.description,
                        stock: c.currentStock,
                        price: c.pricePerUnit,
                        unit: c.unit,
                        isAvailable: c.isAvailable,
                      })),
                    })
                    return editableConsumables.map((consumable, index) => (
                    <tr
                      key={consumable.id || index}
                      className={`border-t border-white/10 hover:bg-white/5 ${
                        consumable.hasChanges ? 'bg-blue-500/10' : ''
                      } ${consumable.isAvailable ? '' : 'opacity-60'}`}
                    >
                      <td className="p-4 text-white/80">{index + 1}</td>

                      {/* Фото */}
                      <td className="p-4 relative">
                        {consumable.imageUrl ? (
                          <div className="relative group w-12 h-12">
                            <Image
                              src={consumable.imageUrl}
                              alt={consumable.name}
                              width={48}
                              height={48}
                              className="w-12 h-12 object-cover rounded border border-white/20 cursor-pointer transition-all duration-300 group-hover:ring-2 group-hover:ring-purple-400/50"
                            />
                            {/* Увеличенная версия при hover */}
                            <div className="absolute top-0 left-0 opacity-0 group-hover:opacity-100 transition-all duration-300 pointer-events-none z-50 transform group-hover:scale-100 scale-75">
                              <div className="relative">
                                <Image
                                  src={consumable.imageUrl}
                                  alt={consumable.name}
                                  width={240}
                                  height={240}
                                  className="w-60 h-60 object-cover rounded-lg border-2 border-purple-400 shadow-2xl shadow-purple-500/30 bg-black/90 backdrop-blur"
                                />
                                <div className="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent rounded-lg"></div>
                                <div className="absolute bottom-2 left-2 right-2 bg-black/60 backdrop-blur rounded px-2 py-1">
                                  <p className="text-white text-xs font-medium truncate">{consumable.name}</p>
                                </div>
                              </div>
                            </div>
                          </div>
                        ) : (
                          <div className="w-12 h-12 bg-white/10 rounded flex items-center justify-center">
                            <Package className="w-5 h-5 text-white/50" />
                          </div>
                        )}
                      </td>

                      {/* Название */}
                      <td className="p-4">
                        <span className="text-white font-medium">{consumable.name}</span>
                      </td>

                      {/* ДОБАВЛЕНО: Название для селлера */}
                      <td className="p-4">
                        {consumable.isEditing ? (
                          <Input
                            type="text"
                            value={consumable.nameForSeller}
                            onChange={(e) => updateField(consumable.id, 'nameForSeller', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder={consumable.name}
                          />
                        ) : (
                          <span className="text-white/80">
                            {consumable.nameForSeller || consumable.name}
                          </span>
                        )}
                      </td>

                      {/* ДОБАВЛЕНО: Артикул V2 */}
                      <td className="p-4">
                        <span className="text-white/80">{consumable.article || '—'}</span>
                      </td>

                      {/* ИСПРАВЛЕНО: Остаток currentStock V2 */}
                      <td className="p-4">
                        <div className="flex items-center gap-2">
                          <span
                            className={`text-sm font-medium ${consumable.isAvailable ? 'text-green-400' : 'text-red-400'}`}
                          >
                            {consumable.currentStock}
                          </span>
                          {!consumable.isAvailable && (
                            <span className="px-2 py-1 rounded-full bg-red-500/20 text-red-300 text-xs">
                              Нет в наличии
                            </span>
                          )}
                        </div>
                      </td>

                      {/* Единица измерения */}
                      <td className="p-4">
                        <span className="text-white/80">{consumable.unit}</span>
                      </td>

                      {/* Цена за единицу */}
                      <td className="p-4">
                        {consumable.isEditing ? (
                          <Input
                            type="number"
                            step="0.01"
                            min="0"
                            value={consumable.pricePerUnit}
                            onChange={(e) => updateField(consumable.id, 'pricePerUnit', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="Не установлена"
                          />
                        ) : (
                          <span className="text-white/80">
                            {consumable.pricePerUnit
                              ? `${parseFloat(consumable.pricePerUnit).toLocaleString()} ₽`
                              : 'Не установлена'}
                          </span>
                        )}
                      </td>

                      {/* Действия */}
                      <td className="p-4">
                        <div className="flex gap-2">
                          {consumable.isEditing ? (
                            <>
                              <Button
                                size="sm"
                                onClick={() => {
                                  saveAllChanges()
                                }}
                                disabled={isSaving}
                                className="h-8 w-8 p-0 bg-gradient-to-r from-green-500/20 to-emerald-500/20 hover:from-green-500/30 hover:to-emerald-500/30 border border-green-500/30 hover:border-green-400/50 text-green-300 hover:text-white transition-all duration-200 shadow-lg shadow-green-500/10 hover:shadow-green-500/20 disabled:opacity-50 disabled:cursor-not-allowed"
                                title="Сохранить"
                              >
                                <Check className="w-4 h-4" />
                              </Button>
                              <Button
                                size="sm"
                                onClick={() => cancelEditing(consumable.id)}
                                className="h-8 w-8 p-0 bg-gradient-to-r from-red-500/20 to-red-600/20 hover:from-red-500/30 hover:to-red-600/30 border border-red-500/30 hover:border-red-400/50 text-red-300 hover:text-white transition-all duration-200 shadow-lg shadow-red-500/10 hover:shadow-red-500/20"
                                title="Отменить"
                              >
                                <X className="w-4 h-4" />
                              </Button>
                            </>
                          ) : (
                            <Button
                              size="sm"
                              onClick={() => startEditing(consumable.id)}
                              className="h-8 w-8 p-0 bg-gradient-to-r from-purple-500/20 to-pink-500/20 hover:from-purple-500/30 hover:to-pink-500/30 border border-purple-500/30 hover:border-purple-400/50 text-purple-300 hover:text-white transition-all duration-200 shadow-lg shadow-purple-500/10 hover:shadow-purple-500/20"
                              title="Редактировать"
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))})()}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </Card>
    </div>
  )
}
