'use client'

import { useQuery, useMutation } from '@apollo/client'
import { TrendingUp, Wrench, Plus, Package2, Clock, CheckCircle, XCircle, Truck } from 'lucide-react'
import { useRouter } from 'next/navigation'
import React, { useState } from 'react'
import { toast } from 'sonner'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { FULFILLMENT_RECEIVE_CONSUMABLE_SUPPLY } from '@/graphql/mutations/fulfillment-receive-v2'
import { GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES } from '@/graphql/queries/fulfillment-consumables-v2'

import { StatsCard } from '../../supplies/ui/stats-card'
import { StatsGrid } from '../../supplies/ui/stats-grid'

// Интерфейс для новой системы поставок v2
interface FulfillmentConsumableSupply {
  id: string
  status: 'PENDING' | 'SUPPLIER_APPROVED' | 'LOGISTICS_CONFIRMED' | 'SHIPPED' | 'IN_TRANSIT' | 'DELIVERED' | 'CANCELLED'
  fulfillmentCenterId: string
  fulfillmentCenter: {
    id: string
    name: string
    inn: string
  }
  supplierId?: string
  supplier?: {
    id: string
    name: string
    inn: string
  }
  requestedDeliveryDate: string
  resalePricePerUnit?: number
  minStockLevel?: number
  notes?: string
  supplierApprovedAt?: string
  packagesCount?: number
  estimatedVolume?: number
  supplierContractId?: string
  supplierNotes?: string
  logisticsPartnerId?: string
  logisticsPartner?: {
    id: string
    name: string
    inn: string
  }
  estimatedDeliveryDate?: string
  routeId?: string
  logisticsCost?: number
  logisticsNotes?: string
  shippedAt?: string
  trackingNumber?: string
  receivedAt?: string
  receivedById?: string
  receivedBy?: {
    id: string
    managerName: string
    phone: string
  }
  actualQuantity?: number
  defectQuantity?: number
  receiptNotes?: string
  items: Array<{
    id: string
    productId: string
    product: {
      id: string
      name: string
      article: string
      price: number
      quantity: number
      mainImage?: string
    }
    requestedQuantity: number
    approvedQuantity?: number
    shippedQuantity?: number
    receivedQuantity?: number
    defectQuantity?: number
    unitPrice: number
    totalPrice: number
  }>
  createdAt: string
  updatedAt: string
}

// Функция для форматирования валюты
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB',
    minimumFractionDigits: 0,
  }).format(amount)
}

// Функция для отображения статуса v2
const getStatusBadge = (status: string) => {
  const statusConfig = {
    PENDING: {
      label: 'Ожидает одобрения поставщика',
      color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30',
      icon: Clock,
    },
    SUPPLIER_APPROVED: {
      label: 'Одобрено поставщиком',
      color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      icon: CheckCircle,
    },
    LOGISTICS_CONFIRMED: {
      label: 'Логистика подтверждена',
      color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
      icon: Truck,
    },
    SHIPPED: {
      label: 'Отправлено',
      color: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      icon: Truck,
    },
    IN_TRANSIT: {
      label: 'В пути',
      color: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      icon: Truck,
    },
    DELIVERED: {
      label: 'Доставлено',
      color: 'bg-green-500/20 text-green-300 border-green-500/30',
      icon: CheckCircle,
    },
    CANCELLED: {
      label: 'Отменено',
      color: 'bg-red-500/20 text-red-300 border-red-500/30',
      icon: XCircle,
    },
  }

  const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.PENDING
  const IconComponent = config.icon

  return (
    <Badge className={`${config.color} flex items-center gap-1`}>
      <IconComponent className="h-3 w-3" />
      {config.label}
    </Badge>
  )
}

// Функция для форматирования даты
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  })
}

export function FulfillmentDetailedSuppliesTab() {
  const router = useRouter()
  const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(new Set())

  // Загружаем поставки расходников через новый API v2
  const { data, loading, error, refetch } = useQuery(GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES, {
    fetchPolicy: 'cache-and-network',
    notifyOnNetworkStatusChange: true,
    errorPolicy: 'all',
    onError: (error) => {
      console.error('❌ GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES Error:', error)
    },
  })

  // Получаем поставки из нового API
  const supplies: FulfillmentConsumableSupply[] = data?.myFulfillmentConsumableSupplies || []

  // Мутация для приемки поставки
  const [fulfillmentReceiveSupply] = useMutation(FULFILLMENT_RECEIVE_CONSUMABLE_SUPPLY, {
    refetchQueries: [{ query: GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES }],
    onCompleted: (data) => {
      if (data.fulfillmentReceiveConsumableSupply.success) {
        toast.success(data.fulfillmentReceiveConsumableSupply.message)
      } else {
        toast.error(data.fulfillmentReceiveConsumableSupply.message)
      }
    },
    onError: (error) => {
      console.error('Error receiving supply:', error)
      toast.error('Ошибка при приемке поставки')
    },
  })

  // Функция для переключения развернутого состояния поставки
  const toggleExpanded = (supplyId: string) => {
    const newExpanded = new Set(expandedSupplies)
    if (newExpanded.has(supplyId)) {
      newExpanded.delete(supplyId)
    } else {
      newExpanded.add(supplyId)
    }
    setExpandedSupplies(newExpanded)
  }

  // Обработчик приемки поставки
  const handleReceiveSupply = async (supply: FulfillmentConsumableSupply) => {
    try {
      // Создаем items для приемки (принимаем все заказанные количества без брака)
      const items = supply.items.map((item) => ({
        id: item.id,
        receivedQuantity: item.requestedQuantity, // Принимаем все заказанное количество
        defectQuantity: 0, // Без брака
      }))

      await fulfillmentReceiveSupply({
        variables: {
          id: supply.id,
          items: items,
          notes: 'Поставка принята на склад',
        },
      })
    } catch (error) {
      console.error('Error receiving supply:', error)
      toast.error('Ошибка при приемке поставки')
    }
  }

  // Вычисляем статистику
  const totalSupplies = supplies.length
  const totalAmount = supplies.reduce((sum, supply) => {
    return sum + supply.items.reduce((itemSum, item) => itemSum + item.totalPrice, 0)
  }, 0)
  const totalItems = supplies.reduce((sum, supply) => {
    return sum + supply.items.reduce((itemSum, item) => itemSum + item.requestedQuantity, 0)
  }, 0)
  const deliveredCount = supplies.filter((supply) => supply.status === 'DELIVERED').length

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent mx-auto mb-3"></div>
          <span className="text-white/60">Загрузка расходников фулфилмента...</span>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <Wrench className="h-12 w-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400 font-medium">Ошибка загрузки расходников</p>
          <p className="text-white/60 text-sm mt-2">{error.message}</p>
          <Button
            onClick={() => refetch()}
            variant="outline"
            className="mt-4 border-white/20 text-white/80 hover:bg-white/10"
          >
            Повторить попытку
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Заголовок с кнопкой создания поставки */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-white mb-1">Расходники фулфилмента</h2>
          <p className="text-white/60 text-sm">Поставки расходников для вашего фулфилмент-центра (система v2)</p>
        </div>
        <Button
          onClick={() => router.push('/supplies/create-fulfillment-consumables-v2')}
          className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white shadow-lg"
        >
          <Plus className="h-4 w-4 mr-2" />
          Создать поставку
        </Button>
      </div>

      {/* Статистика наших расходников */}
      <StatsGrid>
        <StatsCard
          title="Всего поставок"
          value={totalSupplies}
          icon={Package2}
          iconColor="text-orange-400"
          iconBg="bg-orange-500/20"
          subtitle="Заказано нами для склада"
        />

        <StatsCard
          title="Общая сумма"
          value={formatCurrency(totalAmount)}
          icon={TrendingUp}
          iconColor="text-green-400"
          iconBg="bg-green-500/20"
          subtitle="Стоимость всех поставок"
        />

        <StatsCard
          title="Всего единиц"
          value={totalItems}
          icon={Wrench}
          iconColor="text-blue-400"
          iconBg="bg-blue-500/20"
          subtitle="Количество расходников"
        />

        <StatsCard
          title="Доставлено"
          value={deliveredCount}
          icon={CheckCircle}
          iconColor="text-purple-400"
          iconBg="bg-purple-500/20"
          subtitle="Завершенные поставки"
        />
      </StatsGrid>

      {/* Список поставок */}
      {supplies.length === 0 ? (
        <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
          <div className="text-center">
            <Wrench className="h-16 w-16 text-white/20 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">Пока нет поставок расходников</h3>
            <p className="text-white/60">
              Здесь будут отображаться поставки расходников для вашего фулфилмент-центра. Создайте новую поставку через
              кнопку &quot;Создать поставку&quot;.
            </p>
          </div>
        </Card>
      ) : (
        <div className="space-y-4">
          {supplies.map((supply) => (
            <Card key={supply.id} className="bg-white/10 backdrop-blur border-white/20 overflow-hidden">
              {/* Основная информация о поставке */}
              <div
                className="p-6 cursor-pointer hover:bg-white/5 transition-colors"
                onClick={() => toggleExpanded(supply.id)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-4 mb-2">
                      <h3 className="text-lg font-semibold text-white">Поставка #{supply.id.slice(-8)}</h3>
                      {getStatusBadge(supply.status)}
                      {/* Кнопка приемки для статуса SHIPPED */}
                      {supply.status === 'SHIPPED' && (
                        <Button
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleReceiveSupply(supply)
                          }}
                          className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30"
                        >
                          <Package2 className="h-3 w-3 mr-1" />
                          Принять на склад
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-white/60">Поставщик</p>
                        <p className="text-white font-medium">{supply.supplier?.name || 'Не указан'}</p>
                      </div>
                      <div>
                        <p className="text-white/60">Дата поставки</p>
                        <p className="text-white">{formatDate(supply.requestedDeliveryDate)}</p>
                      </div>
                      <div>
                        <p className="text-white/60">Товаров</p>
                        <p className="text-white">{supply.items.length}</p>
                      </div>
                      <div>
                        <p className="text-white/60">Сумма</p>
                        <p className="text-white font-medium">
                          {formatCurrency(supply.items.reduce((sum, item) => sum + item.totalPrice, 0))}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="ml-4">
                    <Clock
                      className={`h-5 w-5 transition-transform ${
                        expandedSupplies.has(supply.id) ? 'rotate-180' : ''
                      } text-white/60`}
                    />
                  </div>
                </div>
              </div>

              {/* Развернутая информация */}
              {expandedSupplies.has(supply.id) && (
                <div className="border-t border-white/20 p-6 bg-white/5">
                  {/* Товары в поставке */}
                  <div className="mb-6">
                    <h4 className="text-white font-semibold mb-4">Товары в поставке</h4>
                    <div className="space-y-3">
                      {supply.items.map((item) => (
                        <div key={item.id} className="flex items-center gap-4 p-4 bg-white/5 rounded-lg">
                          {item.product.mainImage && (
                            <img
                              src={item.product.mainImage}
                              alt={item.product.name}
                              className="h-12 w-12 object-cover rounded-lg"
                            />
                          )}
                          <div className="flex-1">
                            <h5 className="text-white font-medium">{item.product.name}</h5>
                            <p className="text-white/60 text-sm">Артикул: {item.product.article}</p>
                          </div>
                          <div className="text-right">
                            <p className="text-white">Количество: {item.requestedQuantity}</p>
                            <p className="text-white/60 text-sm">
                              {formatCurrency(item.unitPrice)} × {item.requestedQuantity} ={' '}
                              {formatCurrency(item.totalPrice)}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Дополнительная информация */}
                  {(supply.notes || supply.supplierNotes || supply.logisticsNotes) && (
                    <div>
                      <h4 className="text-white font-semibold mb-4">Дополнительная информация</h4>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        {supply.notes && (
                          <div className="p-4 bg-white/5 rounded-lg">
                            <h5 className="text-white/80 font-medium mb-2">Заметки ФФ</h5>
                            <p className="text-white/60 text-sm">{supply.notes}</p>
                          </div>
                        )}
                        {supply.supplierNotes && (
                          <div className="p-4 bg-white/5 rounded-lg">
                            <h5 className="text-white/80 font-medium mb-2">Заметки поставщика</h5>
                            <p className="text-white/60 text-sm">{supply.supplierNotes}</p>
                          </div>
                        )}
                        {supply.logisticsNotes && (
                          <div className="p-4 bg-white/5 rounded-lg">
                            <h5 className="text-white/80 font-medium mb-2">Заметки логистики</h5>
                            <p className="text-white/60 text-sm">{supply.logisticsNotes}</p>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}
