"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 "../ui/stats-card";
import { StatsGrid } from "../ui/stats-grid";
import {
  ChevronDown,
  ChevronRight,
  Calendar,
  MapPin,
  Building2,
  TrendingUp,
  AlertTriangle,
  DollarSign,
  Wrench,
  Box,
  Package2,
  Tags,
} from "lucide-react";

// Типы данных для расходников ФФ
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";
}

// Моковые данные для расходников ФФ
const mockFulfillmentConsumables: FulfillmentConsumableSupply[] = [
  {
    id: "ffc1",
    number: 2001,
    deliveryDate: "2024-01-18",
    createdDate: "2024-01-14",
    status: "delivered",
    plannedTotal: 5000,
    actualTotal: 4950,
    defectTotal: 50,
    totalConsumablesPrice: 125000,
    totalLogisticsPrice: 8000,
    grandTotal: 133000,
    routes: [
      {
        id: "ffcr1",
        from: "Склад расходников",
        fromAddress: "Москва, ул. Промышленная, 12",
        to: "SFERAV Logistics ФФ",
        toAddress: "Москва, ул. Складская, 15",
        totalConsumablesPrice: 125000,
        logisticsPrice: 8000,
        totalAmount: 133000,
        suppliers: [
          {
            id: "ffcs1",
            name: 'ООО "УпакСервис ФФ"',
            inn: "7703456789",
            contact: "+7 (495) 777-88-99",
            address: "Москва, ул. Упаковочная, 5",
            totalAmount: 75000,
            consumables: [
              {
                id: "ffcons1",
                name: "Коробки для ФФ 40x30x15",
                sku: "BOX-FF-403015",
                category: "Упаковка ФФ",
                type: "packaging",
                plannedQty: 2000,
                actualQty: 1980,
                defectQty: 20,
                unitPrice: 45,
                parameters: [
                  {
                    id: "ffcp1",
                    name: "Размер",
                    value: "40x30x15",
                    unit: "см",
                  },
                  {
                    id: "ffcp2",
                    name: "Материал",
                    value: "Гофрокартон усиленный",
                  },
                  { id: "ffcp3", name: "Плотность", value: "5", unit: "слоев" },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
];

export function FulfillmentSuppliesTab() {
  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()
  );

  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={mockFulfillmentConsumables.length}
          icon={Package2}
          iconColor="text-orange-400"
          iconBg="bg-orange-500/20"
          trend={{ value: 5, isPositive: true }}
          subtitle="Поставки материалов"
        />

        <StatsCard
          title="Сумма расходников ФФ"
          value={formatCurrency(
            mockFulfillmentConsumables.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={
            mockFulfillmentConsumables.filter(
              (supply) => supply.status === "in-transit"
            ).length
          }
          icon={Calendar}
          iconColor="text-yellow-400"
          iconBg="bg-yellow-500/20"
          subtitle="Активные поставки"
        />

        <StatsCard
          title="Активные поставки"
          value={
            mockFulfillmentConsumables.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>
              </tr>
            </thead>
            <tbody>
              {mockFulfillmentConsumables.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.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>
  );
}
