"use client";

import React, { useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { StatsCard } from "../../supplies/ui/stats-card";
import { StatsGrid } from "../../supplies/ui/stats-grid";
import { useRouter } from "next/navigation";
import { useQuery } from "@apollo/client";
import { GET_SUPPLY_ORDERS } from "@/graphql/queries";
import { useAuth } from "@/hooks/useAuth";
import {
  Calendar,
  Building2,
  TrendingUp,
  DollarSign,
  Wrench,
  Package2,
  Plus,
  ChevronDown,
  ChevronRight,
} from "lucide-react";

// Интерфейс для заказа
interface SupplyOrder {
  id: string;
  organizationId: string;
  deliveryDate: string;
  createdAt: string;
  totalItems: number;
  totalAmount: number;
  status: string;
  items: {
    id: string;
    quantity: number;
    price: number;
    totalPrice: number;
    product: {
      name: string;
      article: string;
      category?: {
        name: string;
      };
    };
  }[];
}

// Функция для форматирования валюты
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");
};

// Функция для отображения статуса
const getStatusBadge = (status: string) => {
  const statusConfig = {
    PENDING: { label: "Ожидает", color: "bg-yellow-500/20 text-yellow-300 border-yellow-500/30" },
    CONFIRMED: { label: "Подтверждён", color: "bg-blue-500/20 text-blue-300 border-blue-500/30" },
    IN_PROGRESS: { label: "В работе", color: "bg-purple-500/20 text-purple-300 border-purple-500/30" },
    SHIPPED: { label: "Отправлен", color: "bg-orange-500/20 text-orange-300 border-orange-500/30" },
    DELIVERED: { label: "Доставлен", color: "bg-green-500/20 text-green-300 border-green-500/30" },
    CANCELLED: { label: "Отменён", color: "bg-red-500/20 text-red-300 border-red-500/30" },
  };

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

  return (
    <Badge className={config.color}>
      {config.label}
    </Badge>
  );
};

export function FulfillmentDetailedSuppliesTab() {
  const router = useRouter();
  const { user } = useAuth();
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set());

  // Загружаем реальные данные заказов расходников
  const { data, loading, error } = useQuery(GET_SUPPLY_ORDERS, {
    fetchPolicy: 'cache-and-network', // Принудительно проверяем сервер
    notifyOnNetworkStatusChange: true
  });

  // Получаем ID текущей организации (фулфилмент-центра)
  const currentOrganizationId = user?.organization?.id;
  
  // Фильтруем заказы созданные текущей организацией (наши расходники)
  const ourSupplyOrders: SupplyOrder[] = (data?.supplyOrders || []).filter(
    (order: SupplyOrder) => order.organizationId === currentOrganizationId
  );

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

  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-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">
            Управление поставками расходников фулфилмента
          </p>
        </div>
        <Button
          onClick={() => router.push("/fulfillment-supplies/create-consumables")}
          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={ourSupplyOrders.length}
          icon={Package2}
          iconColor="text-orange-400"
          iconBg="bg-orange-500/20"
          subtitle="Поставки расходников"
        />

        <StatsCard
          title="Общая сумма"
          value={formatCurrency(
            ourSupplyOrders.reduce(
              (sum: number, order: SupplyOrder) => sum + order.totalAmount,
              0
            )
          )}
          icon={TrendingUp}
          iconColor="text-green-400"
          iconBg="bg-green-500/20"
          subtitle="Стоимость заказов"
        />

        <StatsCard
          title="Всего единиц"
          value={ourSupplyOrders.reduce((sum: number, order: SupplyOrder) => sum + order.totalItems, 0)}
          icon={Wrench}
          iconColor="text-blue-400"
          iconBg="bg-blue-500/20"
          subtitle="Количество расходников"
        />

        <StatsCard
          title="Завершено"
          value={
            ourSupplyOrders.filter(
              (order: SupplyOrder) => order.status === "DELIVERED"
            ).length
          }
          icon={Calendar}
          iconColor="text-purple-400"
          iconBg="bg-purple-500/20"
          subtitle="Доставленные заказы"
        />
      </StatsGrid>

      {/* Таблица наших расходников */}
      {ourSupplyOrders.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>
      ) : (
        <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>
                </tr>
              </thead>
              <tbody>
                {ourSupplyOrders.map((order: SupplyOrder) => {
                  const isOrderExpanded = expandedOrders.has(order.id);

                  return (
                    <React.Fragment key={order.id}>
                      {/* Основная строка заказа расходников */}
                      <tr
                        className="border-b border-white/10 hover:bg-white/5 transition-colors bg-orange-500/10 cursor-pointer"
                        onClick={() => toggleOrderExpansion(order.id)}
                      >
                        <td className="p-4">
                          <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-bold text-lg">
                              #{order.id.slice(-8)}
                            </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(order.deliveryDate)}
                            </span>
                          </div>
                        </td>
                        <td className="p-4">
                          <span className="text-white/80">
                            {formatDate(order.createdAt)}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-white font-semibold">
                            {order.totalItems}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-white font-semibold">
                            {order.totalItems}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-green-400 font-semibold">
                            {formatCurrency(order.totalAmount)}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-purple-400 font-semibold">
                            -
                          </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(order.totalAmount)}
                            </span>
                          </div>
                        </td>
                        <td className="p-4">{getStatusBadge(order.status)}</td>
                      </tr>

                      {/* Развернутая информация о заказе */}
                      {isOrderExpanded && (
                        <tr>
                          <td colSpan={9} className="p-0">
                            <div className="bg-white/5 border-t border-white/10">
                              <div className="p-6">
                                <h4 className="text-white font-semibold mb-4">
                                  Состав заказа:
                                </h4>
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                  {order.items.map((item) => (
                                    <Card
                                      key={item.id}
                                      className="bg-white/10 backdrop-blur border-white/20 p-4"
                                    >
                                      <div className="space-y-3">
                                        <div>
                                          <h5 className="text-white font-medium mb-1">
                                            {item.product.name}
                                          </h5>
                                          <p className="text-white/60 text-sm">
                                            Артикул: {item.product.article}
                                          </p>
                                          {item.product.category && (
                                            <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-xs mt-2">
                                              {item.product.category.name}
                                            </Badge>
                                          )}
                                        </div>
                                        <div className="flex items-center justify-between">
                                          <div className="text-sm">
                                            <p className="text-white/60">
                                              Количество: {item.quantity} шт
                                            </p>
                                            <p className="text-white/60">
                                              Цена: {formatCurrency(item.price)}
                                            </p>
                                          </div>
                                          <div className="text-right">
                                            <p className="text-green-400 font-semibold">
                                              {formatCurrency(item.totalPrice)}
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    </Card>
                                  ))}
                                </div>
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  );
}
