'use client'

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

import { Badge } from '@/components/ui/badge'
import { Card } from '@/components/ui/card'
import { GET_MY_SELLER_CONSUMABLE_SUPPLIES } from '@/graphql/queries/seller-consumables-v2'
import { useAuthContext } from '@/contexts/AuthContext'

// Типы данных для заказов поставок расходников
interface SupplyOrderItem {
  id: string
  quantity: number
  price: number
  totalPrice: number
  product: {
    id: string
    name: string
    article?: string
    description?: string
    category?: {
      id: string
      name: string
    }
  }
}

interface SupplyOrder {
  id: string
  deliveryDate: string
  status:
    | 'PENDING'
    | 'SUPPLIER_APPROVED'
    | 'CONFIRMED'
    | 'LOGISTICS_CONFIRMED'
    | 'SHIPPED'
    | 'IN_TRANSIT'
    | 'DELIVERED'
    | 'CANCELLED'
  totalAmount: number
  totalItems: number
  consumableType?: 'SELLER_CONSUMABLES' | 'FULFILLMENT_CONSUMABLES'
  createdAt: string
  updatedAt: string
  partner: {
    id: string
    name?: string
    fullName?: string
    inn?: string
    address?: string
    phones?: string[]
    emails?: string[]
  }
  organization: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  fulfillmentCenter?: {
    id: string
    name?: string
    fullName?: string
  }
  items: SupplyOrderItem[]
}

export function SellerSupplyOrdersTab() {
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set())
  const { user } = useAuthContext()

  // Загружаем заказы поставок
  const { data, loading, error } = useQuery(GET_MY_SELLER_CONSUMABLE_SUPPLIES, {
    fetchPolicy: 'cache-and-network',
  })

  const toggleOrderExpansion = (orderId: string) => {
    const newExpanded = new Set(expandedOrders)
    if (newExpanded.has(orderId)) {
      newExpanded.delete(orderId)
    } else {
      newExpanded.add(orderId)
    }
    setExpandedOrders(newExpanded)
  }

  // V2 система - получаем расходники селлера напрямую
  const sellerOrders: SupplyOrder[] = data?.mySellerConsumableSupplies || []

  const getStatusBadge = (status: SupplyOrder['status']) => {
    const statusMap = {
      PENDING: {
        label: 'Ожидает одобрения',
        color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      },
      SUPPLIER_APPROVED: {
        label: 'Одобрена поставщиком',
        color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
      },
      CONFIRMED: {
        label: 'Подтверждена',
        color: 'bg-green-500/20 text-green-300 border-green-500/30',
      },
      LOGISTICS_CONFIRMED: {
        label: 'Готова к отправке',
        color: 'bg-teal-500/20 text-teal-300 border-teal-500/30',
      },
      SHIPPED: {
        label: 'Отправлена',
        color: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      },
      IN_TRANSIT: {
        label: 'В пути',
        color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30',
      },
      DELIVERED: {
        label: 'Доставлена',
        color: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
      },
      CANCELLED: {
        label: 'Отменена',
        color: 'bg-red-500/20 text-red-300 border-red-500/30',
      },
    }
    const config = statusMap[status as keyof typeof statusMap]
    if (!config) {
      // Fallback для неизвестных статусов
      return <Badge className="bg-gray-500/20 text-gray-300 border-gray-500/30 border text-xs">{status}</Badge>
    }
    const { label, color } = config
    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 totalOrders = sellerOrders.length
  const totalAmount = sellerOrders.reduce((sum, order) => sum + (order.totalCostWithDelivery || 0), 0)
  const _totalItems = sellerOrders.reduce((sum, order) => sum + (order.items?.length || 0), 0)
  const pendingOrders = sellerOrders.filter((order) => order.status === 'PENDING').length
  const _approvedOrders = sellerOrders.filter((order) => order.status === 'CONFIRMED').length
  const _inTransitOrders = sellerOrders.filter((order) => order.status === 'IN_TRANSIT').length
  const deliveredOrders = sellerOrders.filter((order) => order.status === 'DELIVERED').length

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
        <span className="ml-3 text-white/60">Загрузка заказов...</span>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <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>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Статистика заказов поставок селлера */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Card className="bg-white/10 backdrop-blur border-white/20 p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-blue-500/20 rounded-lg">
              <Package2 className="h-4 w-4 text-blue-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Всего заказов</p>
              <p className="text-lg font-bold text-white">{totalOrders}</p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-green-500/20 rounded-lg">
              <DollarSign className="h-4 w-4 text-green-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Общая сумма</p>
              <p className="text-lg font-bold text-white">{formatCurrency(totalAmount)}</p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-yellow-500/20 rounded-lg">
              <Clock className="h-4 w-4 text-yellow-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Ожидают</p>
              <p className="text-lg font-bold text-white">{pendingOrders}</p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-purple-500/20 rounded-lg">
              <Truck className="h-4 w-4 text-purple-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Доставлено</p>
              <p className="text-lg font-bold text-white">{deliveredOrders}</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Таблица заказов поставок */}
      <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-3 text-white font-semibold text-sm">№</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Поставщик</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Дата доставки</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Позиций</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Сумма</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Фулфилмент</th>
                <th className="text-left p-3 text-white font-semibold text-sm">Статус</th>
              </tr>
            </thead>
            <tbody>
              {sellerOrders.length === 0 ? (
                <tr>
                  <td colSpan={7} className="text-center py-8">
                    <div className="text-white/60">
                      <Box className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Заказов поставок пока нет</p>
                      <p className="text-sm mt-1">Создайте первый заказ поставки расходников</p>
                    </div>
                  </td>
                </tr>
              ) : (
                sellerOrders.map((order, index) => {
                  const isOrderExpanded = expandedOrders.has(order.id)
                  const orderNumber = sellerOrders.length - index

                  return (
                    <React.Fragment key={order.id}>
                      {/* Основная строка заказа поставки */}
                      <tr
                        className="border-b border-white/10 hover:bg-white/5 transition-colors cursor-pointer"
                        onClick={() => toggleOrderExpansion(order.id)}
                      >
                        <td className="p-3">
                          <div className="flex items-center space-x-2">
                            {isOrderExpanded ? (
                              <ChevronDown className="h-4 w-4 text-white/60" />
                            ) : (
                              <ChevronRight className="h-4 w-4 text-white/60" />
                            )}
                            <span className="text-white font-medium">{orderNumber}</span>
                          </div>
                        </td>
                        <td className="p-3">
                          <div className="flex items-center space-x-2">
                            <Building2 className="h-4 w-4 text-white/40" />
                            <div>
                              <p className="text-white text-sm font-medium">
                                {order.supplier?.name || order.supplier?.fullName || 'Не указан'}
                              </p>
                              {order.supplier?.inn && <p className="text-white/60 text-xs">ИНН: {order.supplier.inn}</p>}
                            </div>
                          </div>
                        </td>
                        <td className="p-3">
                          <div className="flex items-center space-x-2">
                            <Calendar className="h-4 w-4 text-white/40" />
                            <span className="text-white text-sm">{formatDate(order.requestedDeliveryDate)}</span>
                          </div>
                        </td>
                        <td className="p-3">
                          <span className="text-white text-sm">{order.items?.length || 0}</span>
                        </td>
                        <td className="p-3">
                          <span className="text-white text-sm font-medium">{formatCurrency(order.totalCostWithDelivery || 0)}</span>
                        </td>
                        <td className="p-3">
                          <div className="flex items-center space-x-2">
                            <Truck className="h-4 w-4 text-white/40" />
                            <span className="text-white/80 text-sm">
                              {order.fulfillmentCenter?.name || order.fulfillmentCenter?.fullName || 'Не указан'}
                            </span>
                          </div>
                        </td>
                        <td className="p-3">{getStatusBadge(order.status)}</td>
                      </tr>

                      {/* Развернутая информация о заказе */}
                      {isOrderExpanded && (
                        <tr>
                          <td colSpan={7} className="p-0">
                            <div className="bg-white/5 border-t border-white/10">
                              <div className="p-4 space-y-3">
                                <h4 className="text-white font-medium text-sm mb-2">Состав заказа:</h4>
                                <div className="space-y-2">
                                  {order.items.map((item) => (
                                    <div
                                      key={item.id}
                                      className="flex items-center justify-between bg-white/5 rounded-lg p-3"
                                    >
                                      <div className="flex items-center space-x-3">
                                        <Package2 className="h-4 w-4 text-white/40" />
                                        <div>
                                          <p className="text-white text-sm font-medium">{item.product.name}</p>
                                          {item.product.category && (
                                            <p className="text-white/60 text-xs">{item.product.category.name}</p>
                                          )}
                                        </div>
                                      </div>
                                      <div className="text-right">
                                        <p className="text-white text-sm">
                                          {item.quantity} шт × {formatCurrency(item.price)}
                                        </p>
                                        <p className="text-white/60 text-xs">= {formatCurrency(item.totalPrice)}</p>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                                <div className="flex justify-between items-center pt-2 border-t border-white/10">
                                  <span className="text-white/60 text-sm">Создан: {formatDate(order.createdAt)}</span>
                                  <span className="text-white font-medium">
                                    Итого: {formatCurrency(order.totalAmount)}
                                  </span>
                                </div>
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  )
                })
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  )
}
