'use client'

import { useQuery } from '@apollo/client'
import {
  ChevronDown,
  ChevronRight,
  Calendar,
  MapPin,
  Building2,
  TrendingUp,
  AlertTriangle,
  DollarSign,
  Wrench,
  Box,
  Package2,
  Tags,
} from 'lucide-react'
import React, { useState } from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { GET_MY_FULFILLMENT_SUPPLIES } from '@/graphql/queries'

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

// Типы данных для расходников фулфилмента
interface ConsumableParameter {
  id: string
  name: string
  value: string
  unit?: string
}

interface Consumable {
  id: string
  name: string
  sku: string
  category: string
  type: 'packaging' | 'labels' | 'protective' | 'tools' | 'other'
  plannedQty: number
  actualQty: number
  defectQty: number
  unitPrice: number
  parameters: ConsumableParameter[]
}

interface ConsumableSupplier {
  id: string
  name: string
  inn: string
  contact: string
  address: string
  consumables: Consumable[]
  totalAmount: number
}

interface ConsumableRoute {
  id: string
  from: string
  fromAddress: string
  to: string
  toAddress: string
  suppliers: ConsumableSupplier[]
  totalConsumablesPrice: number
  logisticsPrice: number
  totalAmount: number
}

interface FulfillmentConsumableSupply {
  id: string
  number: number
  deliveryDate: string
  createdDate: string
  routes: ConsumableRoute[]
  plannedTotal: number
  actualTotal: number
  defectTotal: number
  totalConsumablesPrice: number
  totalLogisticsPrice: number
  grandTotal: number
  status: 'planned' | 'in-transit' | 'delivered' | 'completed'
}

export function FulfillmentSuppliesTab() {
  // Загружаем реальные данные расходников фулфилмента
  const {
    data: fulfillmentSuppliesData,
    loading,
    error,
  } = useQuery(GET_MY_FULFILLMENT_SUPPLIES, {
    errorPolicy: 'all',
  })

  const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(new Set())
  const [expandedRoutes, setExpandedRoutes] = useState<Set<string>>(new Set())
  const [expandedSuppliers, setExpandedSuppliers] = useState<Set<string>>(new Set())
  const [expandedConsumables, setExpandedConsumables] = useState<Set<string>>(new Set())

  // Преобразуем данные из GraphQL в нужный формат
  const fulfillmentConsumables: FulfillmentConsumableSupply[] = (
    fulfillmentSuppliesData?.myFulfillmentSupplies || []
  ).map((supply: any, index: number) => ({
    id: supply.id,
    number: index + 2000, // Начинаем с 2000 для отличия от товаров
    deliveryDate: supply.date || new Date().toISOString().split('T')[0],
    createdDate: supply.createdAt?.split('T')[0] || new Date().toISOString().split('T')[0],
    status: supply.status === 'active' ? 'delivered' : 'planned',
    plannedTotal: supply.quantity || 0,
    actualTotal: supply.currentStock || 0,
    defectTotal: 0,
    totalConsumablesPrice: supply.price * (supply.quantity || 0),
    totalLogisticsPrice: 0,
    grandTotal: supply.price * (supply.quantity || 0),
    routes: [],
  }))

  const toggleSupplyExpansion = (supplyId: string) => {
    const newExpanded = new Set(expandedSupplies)
    if (newExpanded.has(supplyId)) {
      newExpanded.delete(supplyId)
    } else {
      newExpanded.add(supplyId)
    }
    setExpandedSupplies(newExpanded)
  }

  const toggleRouteExpansion = (routeId: string) => {
    const newExpanded = new Set(expandedRoutes)
    if (newExpanded.has(routeId)) {
      newExpanded.delete(routeId)
    } else {
      newExpanded.add(routeId)
    }
    setExpandedRoutes(newExpanded)
  }

  const toggleSupplierExpansion = (supplierId: string) => {
    const newExpanded = new Set(expandedSuppliers)
    if (newExpanded.has(supplierId)) {
      newExpanded.delete(supplierId)
    } else {
      newExpanded.add(supplierId)
    }
    setExpandedSuppliers(newExpanded)
  }

  const toggleConsumableExpansion = (consumableId: string) => {
    const newExpanded = new Set(expandedConsumables)
    if (newExpanded.has(consumableId)) {
      newExpanded.delete(consumableId)
    } else {
      newExpanded.add(consumableId)
    }
    setExpandedConsumables(newExpanded)
  }

  const getStatusBadge = (status: FulfillmentConsumableSupply['status']) => {
    const statusMap = {
      planned: {
        label: 'Запланирована',
        color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      },
      'in-transit': {
        label: 'В пути',
        color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30',
      },
      delivered: {
        label: 'Доставлена',
        color: 'bg-green-500/20 text-green-300 border-green-500/30',
      },
      completed: {
        label: 'Завершена',
        color: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
      },
    }
    const { label, color } = statusMap[status]
    return <Badge className={`${color} border`}>{label}</Badge>
  }

  const getTypeBadge = (type: Consumable['type']) => {
    const typeMap = {
      packaging: {
        label: 'Расходники',
        color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      },
      labels: {
        label: 'Этикетки',
        color: 'bg-green-500/20 text-green-300 border-green-500/30',
      },
      protective: {
        label: 'Защитная',
        color: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      },
      tools: {
        label: 'Инструменты',
        color: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
      },
      other: {
        label: 'Прочее',
        color: 'bg-gray-500/20 text-gray-300 border-gray-500/30',
      },
    }
    const { label, color } = typeMap[type]
    return <Badge className={`${color} border text-xs`}>{label}</Badge>
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
    }).format(amount)
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }

  const calculateConsumableTotal = (consumable: Consumable) => {
    return consumable.actualQty * consumable.unitPrice
  }

  return (
    <div className="space-y-6">
      {/* Статистика расходников фулфилмента */}
      <StatsGrid>
        <StatsCard
          title="Расходники фулфилмента"
          value={loading ? 0 : fulfillmentConsumables.length}
          icon={Package2}
          iconColor="text-orange-400"
          iconBg="bg-orange-500/20"
          trend={{ value: 5, isPositive: true }}
          subtitle="Поставки материалов"
        />

        <StatsCard
          title="Сумма расходников фулфилмента"
          value={formatCurrency(
            loading ? 0 : fulfillmentConsumables.reduce((sum, supply) => sum + supply.grandTotal, 0),
          )}
          icon={TrendingUp}
          iconColor="text-green-400"
          iconBg="bg-green-500/20"
          trend={{ value: 15, isPositive: true }}
          subtitle="Общая стоимость"
        />

        <StatsCard
          title="В пути"
          value={loading ? 0 : fulfillmentConsumables.filter((supply) => supply.status === 'in-transit').length}
          icon={Calendar}
          iconColor="text-yellow-400"
          iconBg="bg-yellow-500/20"
          subtitle="Активные поставки"
        />

        <StatsCard
          title="Активные поставки"
          value={loading ? 0 : fulfillmentConsumables.filter((supply) => supply.status === 'delivered').length}
          icon={Calendar}
          iconColor="text-blue-400"
          iconBg="bg-blue-500/20"
          trend={{ value: 3, isPositive: true }}
          subtitle="Завершенные поставки"
        />
      </StatsGrid>

      {/* Таблица поставок расходников фулфилмента */}
      <Card className="bg-white/10 backdrop-blur border-white/20 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/20">
                <th className="text-left p-4 text-white font-semibold">№</th>
                <th className="text-left p-4 text-white font-semibold">Дата поставки</th>
                <th className="text-left p-4 text-white font-semibold">Дата создания</th>
                <th className="text-left p-4 text-white font-semibold">Заказано</th>
                {/* СТАРЫЕ СТОЛБЦЫ - ОТКАТ:
                <th className="text-left p-4 text-white font-semibold">План</th>
                <th className="text-left p-4 text-white font-semibold">Факт</th>
                */}
                <th className="text-left p-4 text-white font-semibold">Цена расходников</th>
                <th className="text-left p-4 text-white font-semibold">Логистика</th>
                <th className="text-left p-4 text-white font-semibold">Итого сумма</th>
                <th className="text-left p-4 text-white font-semibold">Статус</th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr>
                  <td colSpan={10} className="p-8 text-center">
                    {/* СТАРЫЙ COLSPAN - ОТКАТ: colSpan={11} */}
                    <div className="text-white/60">Загрузка данных...</div>
                  </td>
                </tr>
              )}
              {!loading && fulfillmentConsumables.length === 0 && (
                <tr>
                  <td colSpan={10} className="p-8 text-center">
                    {/* СТАРЫЙ COLSPAN - ОТКАТ: colSpan={11} */}
                    <div className="text-white/60">
                      <Package2 className="h-12 w-12 mx-auto mb-4 text-white/20" />
                      <div className="text-lg font-semibold text-white mb-2">Расходники фулфилмента не найдены</div>
                      <div>Создайте первую поставку расходников для фулфилмента</div>
                    </div>
                  </td>
                </tr>
              )}
              {!loading &&
                fulfillmentConsumables.map((supply) => {
                  const isSupplyExpanded = expandedSupplies.has(supply.id)

                  return (
                    <React.Fragment key={supply.id}>
                      {/* Основная строка поставки расходников фулфилмента */}
                      <tr
                        className="border-b border-white/10 hover:bg-white/5 transition-colors bg-orange-500/10 cursor-pointer"
                        onClick={() => toggleSupplyExpansion(supply.id)}
                      >
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <span className="text-white font-normal text-lg">{supply.number}</span>
                          </div>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <Calendar className="h-4 w-4 text-white/40" />
                            <span className="text-white font-semibold">{formatDate(supply.deliveryDate)}</span>
                          </div>
                        </td>
                        <td className="p-4">
                          <span className="text-white/80">{formatDate(supply.createdDate)}</span>
                        </td>
                        <td className="p-4">
                          <span className="text-white font-semibold">{supply.plannedTotal}</span>
                        </td>
                        {/* СТАРЫЕ ДАННЫЕ - ОТКАТ:
                        <td className="p-4">
                          <span className="text-white font-semibold">{supply.plannedTotal}</span>
                        </td>
                        <td className="p-4">
                          <span className="text-white font-semibold">{supply.actualTotal}</span>
                        </td>
                        */}
                        <td className="p-4">
                          <span className="text-green-400 font-semibold">
                            {formatCurrency(supply.totalConsumablesPrice)}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-purple-400 font-semibold">
                            {formatCurrency(supply.totalLogisticsPrice)}
                          </span>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <DollarSign className="h-4 w-4 text-white/40" />
                            <span className="text-white font-bold text-lg">{formatCurrency(supply.grandTotal)}</span>
                          </div>
                        </td>
                        <td className="p-4">{getStatusBadge(supply.status)}</td>
                      </tr>
                    </React.Fragment>
                  )
                })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  )
}
