"use client"

import { useState, useEffect, useMemo } from 'react'
import { useQuery, useMutation } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle, 
  AlertDialogTrigger 
} from '@/components/ui/alert-dialog'
import { Plus, Trash2, Save, X, Edit, Check, Truck, Building2, Store, Package, ShoppingCart } from 'lucide-react'
import { toast } from "sonner"
import { useAuth } from '@/hooks/useAuth'
import { GET_MY_LOGISTICS } from '@/graphql/queries'
import { CREATE_LOGISTICS, UPDATE_LOGISTICS, DELETE_LOGISTICS } from '@/graphql/mutations'
import { WildberriesService } from '@/services/wildberries-service'

interface LogisticsRoute {
  id: string
  fromLocation: string
  toLocation: string
  priceUnder1m3: number
  priceOver1m3: number
  description?: string
  createdAt: string
  updatedAt: string
}

interface EditableLogistics {
  id?: string
  fromLocation: string
  toLocation: string
  priceUnder1m3: string
  priceOver1m3: string
  description: string
  isNew: boolean
  isEditing: boolean
  hasChanges: boolean
}

interface LocationOption {
  value: string
  label: string
}

// Базовые локации (без своего фулфилмента)
const BASE_LOCATIONS = {
  markets: [
    { value: 'sadovod', label: 'Садовод' },
    { value: 'tyak-moscow', label: 'ТЯК Москва' }
  ],
  wbWarehouses: [
    // Статичные склады WB как fallback
    { value: 'wb-warehouse-1', label: 'Подольск' },
    { value: 'wb-warehouse-2', label: 'Электросталь' },
    { value: 'wb-warehouse-3', label: 'Коледино' }
  ],
  ozonWarehouses: [
    // Статичные склады Ozon
    { value: 'ozon-warehouse-1', label: 'Тверь' },
    { value: 'ozon-warehouse-2', label: 'Казань' }
  ]
}

export function LogisticsTab() {
  const { user } = useAuth()
  const [editableLogistics, setEditableLogistics] = useState<EditableLogistics[]>([])
  const [isSaving, setIsSaving] = useState(false)
  const [isInitialized, setIsInitialized] = useState(false)
  const [warehouses, setWarehouses] = useState<LocationOption[]>([])

  // GraphQL запросы и мутации
  const { data, loading, error, refetch } = useQuery(GET_MY_LOGISTICS, {
    skip: user?.organization?.type !== 'FULFILLMENT'
  })
  const [createLogistics] = useMutation(CREATE_LOGISTICS)
  const [updateLogistics] = useMutation(UPDATE_LOGISTICS)
  const [deleteLogistics] = useMutation(DELETE_LOGISTICS)

  const logistics = data?.myLogistics || []

  // Загружаем склады из API WB
  useEffect(() => {
    const loadWarehouses = async () => {
      try {
        // Получаем API ключ из организации пользователя
        const wbApiKey = user?.organization?.apiKeys?.find(key => key.marketplace === 'WILDBERRIES')
        if (wbApiKey?.isActive && wbApiKey.validationData) {
          const validationData = wbApiKey.validationData as Record<string, string>
          const apiToken = validationData?.token || validationData?.apiKey
          if (apiToken) {
            const wbWarehouses = await WildberriesService.getWarehouses(apiToken)
            const warehouseOptions = wbWarehouses.map(w => ({
              value: `wb-${w.id}`,
              label: `Склад WB ${w.name}`
            }))
            setWarehouses(warehouseOptions)
            console.log('Loaded WB warehouses:', warehouseOptions)
          }
        }
      } catch (error) {
        console.error('Failed to load warehouses:', error)
        // Используем только статичные склады
      }
    }

    if (user?.organization) {
      loadWarehouses()
    }
  }, [user])

  // Преобразуем загруженные маршруты в редактируемый формат
  useEffect(() => {
    if (data?.myLogistics && !isInitialized) {
      const convertedLogistics: EditableLogistics[] = data.myLogistics.map((route: LogisticsRoute) => ({
        id: route.id,
        fromLocation: route.fromLocation,
        toLocation: route.toLocation,
        priceUnder1m3: route.priceUnder1m3.toString(),
        priceOver1m3: route.priceOver1m3.toString(),
        description: route.description || '',
        isNew: false,
        isEditing: false,
        hasChanges: false
      }))
      
      setEditableLogistics(convertedLogistics)
      setIsInitialized(true)
    }
  }, [data, isInitialized])

  // Получить все опции локаций с группировкой
  const getAllLocationOptions = () => {
    const myFulfillment = user?.organization?.name ? [
      { value: 'my-fulfillment', label: user.organization.name }
    ] : []
    
    return [
      ...myFulfillment,
      ...BASE_LOCATIONS.markets,
      ...BASE_LOCATIONS.wbWarehouses,
      ...BASE_LOCATIONS.ozonWarehouses,
      ...warehouses
    ]
  }

  // Создать группированные опции для селекта
  const getGroupedLocationOptions = () => {
    const myFulfillment = user?.organization?.name ? [
      { value: 'my-fulfillment', label: user.organization.name }
    ] : []
    
    return {
      myFulfillment,
      markets: BASE_LOCATIONS.markets,
      wbWarehouses: [...BASE_LOCATIONS.wbWarehouses, ...warehouses],
      ozonWarehouses: BASE_LOCATIONS.ozonWarehouses
    }
  }

  // Получить название локации по ID
  const getLocationLabel = (locationId: string) => {
    const allOptions = getAllLocationOptions()
    return allOptions.find(opt => opt.value === locationId)?.label || locationId
  }

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

  // Удалить строку
  const removeRow = async (routeId: string, isNew: boolean) => {
    if (isNew) {
      setEditableLogistics(prev => prev.filter(r => r.id !== routeId))
    } else {
      try {
        await deleteLogistics({ 
          variables: { id: routeId },
          update: (cache, { data }) => {
            if (data?.deleteLogistics) {
              const existingData = cache.readQuery({ query: GET_MY_LOGISTICS }) as { myLogistics: LogisticsRoute[] } | null
              if (existingData && existingData.myLogistics) {
                cache.writeQuery({
                  query: GET_MY_LOGISTICS,
                  data: {
                    myLogistics: existingData.myLogistics.filter((route: LogisticsRoute) => route.id !== routeId)
                  }
                })
              }
            }
          }
        })
        setEditableLogistics(prev => prev.filter(r => r.id !== routeId))
        toast.success('Маршрут успешно удален')
      } catch (error) {
        console.error('Error deleting logistics:', error)
        toast.error('Ошибка при удалении маршрута')
      }
    }
  }

  // Начать редактирование
  const startEditing = (routeId: string) => {
    setEditableLogistics(prev => 
      prev.map(route => 
        route.id === routeId ? { ...route, isEditing: true } : route
      )
    )
  }

  // Отменить редактирование
  const cancelEditing = (routeId: string) => {
    const route = editableLogistics.find(r => r.id === routeId)
    if (!route) return
    
    if (route.isNew) {
      setEditableLogistics(prev => prev.filter(r => r.id !== routeId))
    } else {
      const originalRoute = logistics.find((r: LogisticsRoute) => r.id === route.id)
      if (originalRoute) {
        setEditableLogistics(prev => 
          prev.map(r => 
            r.id === routeId 
              ? {
                  id: originalRoute.id,
                  fromLocation: originalRoute.fromLocation,
                  toLocation: originalRoute.toLocation,
                  priceUnder1m3: originalRoute.priceUnder1m3.toString(),
                  priceOver1m3: originalRoute.priceOver1m3.toString(),
                  description: originalRoute.description || '',
                  isNew: false,
                  isEditing: false,
                  hasChanges: false
                }
              : r
          )
        )
      }
    }
  }

  // Обновить поле
  const updateField = (routeId: string, field: keyof EditableLogistics, value: string) => {
    setEditableLogistics(prev => 
      prev.map((route) => {
        if (route.id !== routeId) return route
        
        const updated = { ...route, hasChanges: true }
        if (field === 'fromLocation') updated.fromLocation = value
        else if (field === 'toLocation') updated.toLocation = value
        else if (field === 'priceUnder1m3') updated.priceUnder1m3 = value
        else if (field === 'priceOver1m3') updated.priceOver1m3 = value
        else if (field === 'description') updated.description = value
        
        return updated
      })
    )
  }

  // Сохранить все изменения
  const saveAllChanges = async () => {
    setIsSaving(true)
    console.log('Saving all changes...')
    
    try {
      const routesToSave = editableLogistics.filter(r => {
        if (r.isNew) {
          return r.fromLocation && r.toLocation && r.priceUnder1m3 && r.priceOver1m3
        }
        return r.hasChanges
      })
      
      console.log('Routes to save:', routesToSave)
      
      for (const route of routesToSave) {
        if (!route.fromLocation || !route.toLocation || !route.priceUnder1m3 || !route.priceOver1m3) {
          toast.error('Заполните все обязательные поля')
          setIsSaving(false)
          return
        }

        const input = {
          fromLocation: route.fromLocation,
          toLocation: route.toLocation,
          priceUnder1m3: parseFloat(route.priceUnder1m3),
          priceOver1m3: parseFloat(route.priceOver1m3),
          description: route.description || undefined
        }

        console.log('Saving route with input:', input)

        if (route.isNew) {
          const result = await createLogistics({ 
            variables: { input },
            update: (cache, { data }) => {
              if (data?.createLogistics?.success && data.createLogistics.logistics) {
                const existingData = cache.readQuery({ query: GET_MY_LOGISTICS }) as { myLogistics: LogisticsRoute[] } | null
                if (existingData && existingData.myLogistics) {
                  cache.writeQuery({
                    query: GET_MY_LOGISTICS,
                    data: {
                      myLogistics: [...existingData.myLogistics, data.createLogistics.logistics]
                    }
                  })
                }
              }
            }
          })
          console.log('Create result:', result)
        } else if (route.id) {
          const result = await updateLogistics({ 
            variables: { id: route.id, input },
            update: (cache, { data }) => {
              if (data?.updateLogistics?.success && data.updateLogistics.logistics) {
                const existingData = cache.readQuery({ query: GET_MY_LOGISTICS }) as { myLogistics: LogisticsRoute[] } | null
                if (existingData && existingData.myLogistics) {
                  cache.writeQuery({
                    query: GET_MY_LOGISTICS,
                    data: {
                      myLogistics: existingData.myLogistics.map((route: LogisticsRoute) => 
                        route.id === data.updateLogistics.logistics.id ? data.updateLogistics.logistics : route
                      )
                    }
                  })
                }
              }
            }
          })
          console.log('Update result:', result)
        }
      }

      toast.success('Все изменения успешно сохранены')
      // Обновляем локальное состояние - убираем флаги isNew и hasChanges
      setEditableLogistics(prev => prev.map(route => ({
        ...route,
        isNew: false,
        hasChanges: false,
        isEditing: false
      })))
    } catch (error) {
      console.error('Error saving changes:', error)
      toast.error(`Ошибка при сохранении: ${error}`)
    } finally {
      setIsSaving(false)
    }
  }

  // Проверяем есть ли несохраненные изменения
  const hasUnsavedChanges = useMemo(() => {
    return editableLogistics.some(r => {
      if (r.isNew) {
        return r.fromLocation || r.toLocation || r.priceUnder1m3 || r.priceOver1m3
      }
      return r.hasChanges
    })
  }, [editableLogistics])

  // Компонент группированного селекта
  const GroupedLocationSelect = ({ value, onValueChange, placeholder }: {
    value: string
    onValueChange: (value: string) => void
    placeholder: string
  }) => {
    const groups = getGroupedLocationOptions()
    
    return (
      <Select value={value} onValueChange={onValueChange}>
        <SelectTrigger className="bg-white/5 border-white/20 text-white">
          <SelectValue placeholder={placeholder} />
        </SelectTrigger>
        <SelectContent>
          {/* Мой фулфилмент */}
          {groups.myFulfillment.length > 0 && (
            <>
              <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/50 flex items-center gap-2">
                <Building2 className="w-3 h-3" />
                Мой фулфилмент
              </div>
              {groups.myFulfillment.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </>
          )}
          
          {/* Рынки */}
          <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/50 flex items-center gap-2">
            <Store className="w-3 h-3" />
            Рынки
          </div>
          {groups.markets.map(option => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
          
          {/* Склады Wildberries */}
          <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/50 flex items-center gap-2">
            <Package className="w-3 h-3" />
            Склады Wildberries
          </div>
          {groups.wbWarehouses.map((option: LocationOption) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
          
          {/* Склады Ozon */}
          <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/50 flex items-center gap-2">
            <ShoppingCart className="w-3 h-3" />
            Склады Ozon
          </div>
          {groups.ozonWarehouses.map((option: LocationOption) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    )
  }

  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">
                  <Truck className="w-8 h-8 text-white/50" />
                </div>
                <p className="text-white/70 text-sm">Загрузка маршрутов...</p>
              </div>
            </div>
          ) : editableLogistics.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">До 1м³ (₽) *</th>
                    <th className="text-left p-4 text-white font-medium">Свыше 1м³ (₽) *</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>
                  {editableLogistics.map((route, index) => (
                    <tr key={route.id || index} className={`border-t border-white/10 hover:bg-white/5 ${route.isNew || route.hasChanges ? 'bg-blue-500/10' : ''}`}>
                      <td className="p-4 text-white/80">{index + 1}</td>
                      
                      {/* Откуда */}
                      <td className="p-4">
                        {route.isEditing ? (
                          <GroupedLocationSelect
                            value={route.fromLocation}
                            onValueChange={(value) => updateField(route.id!, 'fromLocation', value)}
                            placeholder="Выберите точку отправления"
                          />
                        ) : (
                          <span className="text-white/80">{getLocationLabel(route.fromLocation)}</span>
                        )}
                      </td>
                      
                      {/* Куда */}
                      <td className="p-4">
                        {route.isEditing ? (
                          <GroupedLocationSelect
                            value={route.toLocation}
                            onValueChange={(value) => updateField(route.id!, 'toLocation', value)}
                            placeholder="Выберите точку назначения"
                          />
                        ) : (
                          <span className="text-white/80">{getLocationLabel(route.toLocation)}</span>
                        )}
                      </td>
                      
                      {/* Цена до 1м³ */}
                      <td className="p-4">
                        {route.isEditing ? (
                          <Input
                            type="number"
                            step="0.01"
                            min="0"
                            value={route.priceUnder1m3}
                            onChange={(e) => updateField(route.id!, 'priceUnder1m3', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="0.00"
                          />
                        ) : (
                          <span className="text-white/80">
                            {route.priceUnder1m3 ? parseFloat(route.priceUnder1m3).toLocaleString() : '0'} ₽
                          </span>
                        )}
                      </td>
                      
                      {/* Цена свыше 1м³ */}
                      <td className="p-4">
                        {route.isEditing ? (
                          <Input
                            type="number"
                            step="0.01"
                            min="0"
                            value={route.priceOver1m3}
                            onChange={(e) => updateField(route.id!, 'priceOver1m3', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="0.00"
                          />
                        ) : (
                          <span className="text-white/80">
                            {route.priceOver1m3 ? parseFloat(route.priceOver1m3).toLocaleString() : '0'} ₽
                          </span>
                        )}
                      </td>
                      
                      {/* Описание */}
                      <td className="p-4">
                        {route.isEditing ? (
                          <Input
                            value={route.description}
                            onChange={(e) => updateField(route.id!, 'description', e.target.value)}
                            className="bg-white/5 border-white/20 text-white"
                            placeholder="Дополнительная информация"
                          />
                        ) : (
                          <span className="text-white/80">{route.description || '—'}</span>
                        )}
                      </td>
                      
                      {/* Действия */}
                      <td className="p-4">
                        <div className="flex gap-2">
                          {route.isEditing ? (
                            <>
                              <Button
                                size="sm"
                                onClick={() => {
                                  if (route.fromLocation && route.toLocation && route.priceUnder1m3 && route.priceOver1m3) {
                                    saveAllChanges()
                                  } else {
                                    toast.error('Заполните обязательные поля')
                                  }
                                }}
                                disabled={!route.fromLocation || !route.toLocation || !route.priceUnder1m3 || !route.priceOver1m3 || 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(route.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(route.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">
                                  Вы действительно хотите удалить маршрут? Это действие необратимо.
                                </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(route.id!, route.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>
  )
} 