'use client'

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

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
// V2 импорты
import { 
  GET_MY_FULFILLMENT_SERVICES_V2,
  CREATE_FULFILLMENT_SERVICE,
  UPDATE_FULFILLMENT_SERVICE,
  DELETE_FULFILLMENT_SERVICE,
} from '@/graphql/queries/fulfillment-services-v2'
import { useAuthContext } from '@/contexts/AuthContext'

interface Service {
  id: string
  name: string
  description?: string
  price: number
  imageUrl?: string
  createdAt: string
  updatedAt: string
}

interface EditableService {
  id?: string // undefined для новых записей
  name: string
  description: string
  price: string
  imageUrl: string
  imageFile?: File
  isNew: boolean
  isEditing: boolean
  hasChanges: boolean
}

interface PendingChange extends EditableService {
  isDeleted?: boolean
}

export function ServicesTab() {
  const { user } = useAuthContext()
  const [editableServices, setEditableServices] = useState<EditableService[]>([])
  const [pendingChanges, setPendingChanges] = useState<PendingChange[]>([])
  const [isSaving, setIsSaving] = useState(false)
  const [isInitialized, setIsInitialized] = useState(false)

  // GraphQL запросы и мутации
  const { data, loading, error, refetch } = useQuery(GET_MY_FULFILLMENT_SERVICES_V2, {
    skip: user?.organization?.type !== 'FULFILLMENT',
  })
  const [createService] = useMutation(CREATE_FULFILLMENT_SERVICE)
  const [updateService] = useMutation(UPDATE_FULFILLMENT_SERVICE)
  const [deleteService] = useMutation(DELETE_FULFILLMENT_SERVICE)

  const services = data?.myFulfillmentServices || []

  // Преобразуем загруженные услуги в редактируемый формат
  useEffect(() => {
    if (data?.myFulfillmentServices && !isInitialized) {
      const convertedServices: EditableService[] = data.myFulfillmentServices.map((service: Service) => ({
        id: service.id,
        name: service.name,
        description: service.description || '',
        price: service.price.toString(),
        imageUrl: service.imageUrl || '',
        isNew: false,
        isEditing: false,
        hasChanges: false,
      }))

      setEditableServices(convertedServices)
      setPendingChanges([])
      setIsInitialized(true)
    }
  }, [data, isInitialized])

  // Добавить новую строку
  const addNewRow = () => {
    const tempId = `temp-${Date.now()}-${Math.random()}`
    const newRow: EditableService = {
      id: tempId,
      name: '',
      description: '',
      price: '',
      imageUrl: '',
      isNew: true,
      isEditing: true,
      hasChanges: false,
    }
    setEditableServices((prev) => [...prev, newRow])
  }

  // Удалить строку
  const removeRow = async (serviceId: string, isNew: boolean) => {
    if (isNew) {
      // Просто удаляем из массива если это новая строка
      setEditableServices((prev) => prev.filter((s) => s.id !== serviceId))
    } else {
      // Удаляем существующую запись сразу
      try {
        await deleteService({
          variables: { id: serviceId },
          update: (cache, { data }) => {
            // Обновляем кэш Apollo Client
            const existingData = cache.readQuery({ query: GET_MY_FULFILLMENT_SERVICES_V2 }) as { myFulfillmentServices: Service[] } | null
            if (existingData && data) {
              cache.writeQuery({
                query: GET_MY_FULFILLMENT_SERVICES_V2,
                data: {
                  myFulfillmentServices: existingData.myFulfillmentServices.filter((s: Service) => s.id !== serviceId),
                },
              })
            }
          },
        })

        // Удаляем из локального состояния по ID, а не по индексу
        setEditableServices((prev) => prev.filter((s) => s.id !== serviceId))
        toast.success('Услуга успешно удалена')
      } catch (error) {
        console.error('Error deleting service:', error)
        toast.error('Ошибка при удалении услуги')
      }
    }
  }

  // Начать редактирование существующей строки
  const startEditing = (serviceId: string) => {
    setEditableServices((prev) =>
      prev.map((service) => (service.id === serviceId ? { ...service, isEditing: true } : service)),
    )
  }

  // Отменить редактирование
  const cancelEditing = (serviceId: string) => {
    const service = editableServices.find((s) => s.id === serviceId)
    if (!service) return

    if (service.isNew) {
      // Удаляем новую строку
      setEditableServices((prev) => prev.filter((s) => s.id !== serviceId))
    } else {
      // Возвращаем к исходному состоянию
      const originalService = services.find((s: Service) => s.id === service.id)
      if (originalService) {
        setEditableServices((prev) =>
          prev.map((s) =>
            s.id === serviceId
              ? {
                  id: originalService.id,
                  name: originalService.name,
                  description: originalService.description || '',
                  price: originalService.price.toString(),
                  imageUrl: originalService.imageUrl || '',
                  isNew: false,
                  isEditing: false,
                  hasChanges: false,
                }
              : s,
          ),
        )
      }
    }
  }

  // Обновить поле
  const updateField = (serviceId: string, field: keyof EditableService, value: string | File) => {
    setEditableServices((prev) =>
      prev.map((service) => {
        if (service.id !== serviceId) return service

        const updated = { ...service, hasChanges: true }
        if (field === 'imageFile' && value instanceof File) {
          updated.imageFile = value
          updated.imageUrl = URL.createObjectURL(value)
        } else if (typeof value === 'string') {
          if (field === 'name') updated.name = value
          else if (field === 'description') updated.description = value
          else if (field === 'price') updated.price = value
          else if (field === 'imageUrl') updated.imageUrl = value
        }
        return updated
      }),
    )
  }

  // Загрузка изображения
  const uploadImageAndGetUrl = async (file: File): Promise<string> => {
    if (!user?.id) throw new Error('User not found')

    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user.id)
    formData.append('type', 'service')

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

    if (!response.ok) {
      throw new Error('Failed to upload image')
    }

    const result = await response.json()
    return result.url
  }

  // Сохранить все изменения
  const saveAllChanges = async () => {
    setIsSaving(true)
    try {
      const servicesToSave = editableServices.filter((s) => {
        if (s.isNew) {
          // Для новых записей проверяем что обязательные поля заполнены
          return s.name.trim() && s.price
        }
        // Для существующих записей проверяем флаг изменений
        return s.hasChanges
      })

      console.warn('Services to save:', servicesToSave.length, servicesToSave)

      for (const service of servicesToSave) {
        if (!service.name.trim() || !service.price) {
          toast.error('Заполните обязательные поля для всех услуг')
          setIsSaving(false)
          return
        }

        let imageUrl = service.imageUrl

        // Загружаем изображение если выбрано
        if (service.imageFile) {
          imageUrl = await uploadImageAndGetUrl(service.imageFile)
        }

        const input = {
          name: service.name,
          description: service.description || undefined,
          price: parseFloat(service.price),
          imageUrl: imageUrl || undefined,
        }

        if (service.isNew) {
          await createService({
            variables: { input },
            update: (cache, { data }) => {
              if (data?.createFulfillmentService?.success && data.createFulfillmentService.service) {
                const existingData = cache.readQuery({ query: GET_MY_FULFILLMENT_SERVICES_V2 }) as { myFulfillmentServices: Service[] } | null
                if (existingData) {
                  cache.writeQuery({
                    query: GET_MY_FULFILLMENT_SERVICES_V2,
                    data: {
                      myFulfillmentServices: [...existingData.myFulfillmentServices, data.createFulfillmentService.service],
                    },
                  })
                }
              }
            },
          })
        } else if (service.id) {
          await updateService({
            variables: { input: { id: service.id, ...input } },
            update: (cache, { data }) => {
              if (data?.updateFulfillmentService?.success && data.updateFulfillmentService.service) {
                const existingData = cache.readQuery({ query: GET_MY_FULFILLMENT_SERVICES_V2 }) as { myFulfillmentServices: Service[] } | null
                if (existingData) {
                  cache.writeQuery({
                    query: GET_MY_FULFILLMENT_SERVICES_V2,
                    data: {
                      myFulfillmentServices: existingData.myFulfillmentServices.map((s: Service) =>
                        s.id === data.updateFulfillmentService.service.id ? data.updateFulfillmentService.service : s,
                      ),
                    },
                  })
                }
              }
            },
          })
        }
      }

      // Удаления теперь происходят сразу в removeRow, так что здесь обрабатываем только обновления

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

  // Проверяем есть ли несохраненные изменения
  const hasUnsavedChanges = useMemo(() => {
    return editableServices.some((s) => {
      if (s.isNew) {
        // Для новых записей проверяем что есть данные для сохранения
        return s.name.trim() || s.price || s.description.trim()
      }
      return s.hasChanges
    })
  }, [editableServices])

  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">
            <Button
              onClick={addNewRow}
              className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white border-0 shadow-lg shadow-purple-500/25 hover:shadow-purple-500/40 transition-all duration-300 hover:scale-105"
            >
              <Plus className="w-4 h-4 mr-2" />
              Добавить услугу
            </Button>

            {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 ? (
            <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">Загрузка услуг...</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">Не удалось загрузить услуги</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>
          ) : editableServices.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">
                  <Plus 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>
                <Button
                  onClick={addNewRow}
                  className="bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  Добавить услугу
                </Button>
              </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>
                  </tr>
                </thead>
                <tbody>
                  {editableServices.map((service, index) => (
                    <tr
                      key={service.id || index}
                      className={`border-t border-white/10 hover:bg-white/5 ${service.isNew || service.hasChanges ? 'bg-blue-500/10' : ''}`}
                    >
                      <td className="p-4 text-white/80">{index + 1}</td>

                      {/* Фото */}
                      <td className="p-4 relative">
                        {service.isEditing ? (
                          <div className="flex items-center gap-3">
                            <Input
                              type="file"
                              accept="image/*"
                              onChange={(e) => {
                                const file = e.target.files?.[0]
                                if (file) {
                                  updateField(service.id!, 'imageFile', file)
                                }
                              }}
                              className="bg-white/5 border-white/20 text-white text-xs file:bg-gradient-to-r file:from-purple-500 file:to-pink-500 file:text-white file:border-0 file:rounded file:px-2 file:py-1 file:mr-2 file:text-xs flex-1"
                            />
                            {service.imageUrl && (
                              <div className="relative group w-12 h-12 flex-shrink-0">
                                <Image
                                  src={service.imageUrl}
                                  alt="Preview"
                                  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={service.imageUrl}
                                      alt="Preview"
                                      width={200}
                                      height={200}
                                      className="w-50 h-50 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>
                                </div>
                              </div>
                            )}
                          </div>
                        ) : service.imageUrl ? (
                          <div className="relative group w-12 h-12">
                            <Image
                              src={service.imageUrl}
                              alt={service.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={service.imageUrl}
                                  alt={service.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">{service.name}</p>
                                </div>
                              </div>
                            </div>
                          </div>
                        ) : (
                          <div className="w-12 h-12 bg-white/10 rounded flex items-center justify-center">
                            <Upload className="w-5 h-5 text-white/50" />
                          </div>
                        )}
                      </td>

                      {/* Название */}
                      <td className="p-4">
                        {service.isEditing ? (
                          <Input
                            value={service.name}
                            onChange={(e) => updateField(service.id!, 'name', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="Название услуги"
                          />
                        ) : (
                          <span className="text-white font-medium">{service.name}</span>
                        )}
                      </td>

                      {/* Цена */}
                      <td className="p-4">
                        {service.isEditing ? (
                          <Input
                            type="number"
                            step="0.01"
                            min="0"
                            value={service.price}
                            onChange={(e) => updateField(service.id!, 'price', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="0.00"
                          />
                        ) : (
                          <span className="text-white/80">
                            {service.price ? parseFloat(service.price).toLocaleString() : '0'} ₽
                          </span>
                        )}
                      </td>

                      {/* Описание */}
                      <td className="p-4">
                        {service.isEditing ? (
                          <Input
                            value={service.description}
                            onChange={(e) => updateField(service.id!, 'description', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="Описание услуги"
                          />
                        ) : (
                          <span className="text-white/80">{service.description || '—'}</span>
                        )}
                      </td>

                      {/* Действия */}
                      <td className="p-4">
                        <div className="flex gap-2">
                          {service.isEditing ? (
                            <>
                              <Button
                                size="sm"
                                onClick={() => {
                                  // Сохраняем только эту услугу если заполнены обязательные поля
                                  if (service.name.trim() && service.price) {
                                    saveAllChanges()
                                  } else {
                                    toast.error('Заполните обязательные поля')
                                  }
                                }}
                                disabled={!service.name.trim() || !service.price || 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(service.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(service.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>
                          )}

                          <AlertDialog>
                            <AlertDialogTrigger asChild>
                              <Button
                                size="sm"
                                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="Удалить"
                              >
                                <Trash2 className="w-4 h-4" />
                              </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent className="bg-gradient-to-br from-red-900/95 via-red-800/95 to-red-900/95 backdrop-blur-xl border border-red-500/30 text-white shadow-2xl shadow-red-500/20">
                              <AlertDialogHeader>
                                <AlertDialogTitle className="text-xl font-bold bg-gradient-to-r from-red-300 to-red-300 bg-clip-text text-transparent">
                                  Подтвердите удаление
                                </AlertDialogTitle>
                                <AlertDialogDescription className="text-red-200">
                                  Вы действительно хотите удалить услугу &ldquo;{service.name}&rdquo;? Это действие
                                  необратимо.
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter className="gap-3">
                                <AlertDialogCancel className="border-red-400/30 text-red-200 hover:bg-red-500/10 hover:border-red-300 transition-all duration-300">
                                  Отмена
                                </AlertDialogCancel>
                                <AlertDialogAction
                                  onClick={() => removeRow(service.id!, service.isNew)}
                                  className="bg-gradient-to-r from-red-600 to-red-700 hover:from-red-700 hover:to-red-800 text-white border-0 shadow-lg shadow-red-500/25 hover:shadow-red-500/40 transition-all duration-300"
                                >
                                  Удалить
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </Card>
    </div>
  )
}
