"use client";

import React, { useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";

import { Sidebar } from "@/components/dashboard/sidebar";
import { useSidebar } from "@/hooks/useSidebar";
import { useQuery } from "@apollo/client";
import { GET_MY_SUPPLIES } from "@/graphql/queries";
import {
  ArrowLeft,
  Search,
  Filter,
  SortAsc,
  SortDesc,
  Package,
  Wrench,
  AlertTriangle,
  CheckCircle,
  Clock,
  TrendingUp,
  TrendingDown,
  BarChart3,
  Grid3X3,
  List,
  Download,
  Eye,
  Calendar,
  MapPin,
  User,
  DollarSign,
  Hash,
  Activity,
  Layers,
  PieChart,
  FileSpreadsheet,
  Zap,
  Target,
  Sparkles,
  Truck,
  ChevronRight,
  ChevronDown,
} from "lucide-react";
import { toast } from "sonner";

// Типы данных
interface Supply {
  id: string;
  name: string;
  description: string;
  price: number;
  quantity: number;
  unit: string;
  category: string;
  status: string;
  date: string;
  supplier: string;
  minStock: number;
  currentStock: number;
  imageUrl?: string;
  createdAt: string;
  updatedAt: string;
}

interface FilterState {
  search: string;
  category: string;
  status: string;
  supplier: string;
  lowStock: boolean;
}

interface SortState {
  field: keyof Supply;
  direction: "asc" | "desc";
}

// Статусы расходников с цветами
const STATUS_CONFIG = {
  available: {
    label: "Доступен",
    color: "bg-green-500/20 text-green-300",
    icon: CheckCircle,
  },
  "low-stock": {
    label: "Мало на складе",
    color: "bg-yellow-500/20 text-yellow-300",
    icon: AlertTriangle,
  },
  "out-of-stock": {
    label: "Нет в наличии",
    color: "bg-red-500/20 text-red-300",
    icon: AlertTriangle,
  },
  "in-transit": {
    label: "В пути",
    color: "bg-blue-500/20 text-blue-300",
    icon: Clock,
  },
  reserved: {
    label: "Зарезервирован",
    color: "bg-purple-500/20 text-purple-300",
    icon: Package,
  },
} as const;

export function FulfillmentSuppliesPage() {
  const router = useRouter();
  const { getSidebarMargin } = useSidebar();

  // Состояния
  const [viewMode, setViewMode] = useState<"grid" | "list" | "analytics">(
    "grid"
  );
  const [filters, setFilters] = useState<FilterState>({
    search: "",
    category: "",
    status: "",
    supplier: "",
    lowStock: false,
  });
  const [sort, setSort] = useState<SortState>({
    field: "name",
    direction: "asc",
  });
  const [showFilters, setShowFilters] = useState(false);
  const [groupBy, setGroupBy] = useState<
    "none" | "category" | "status" | "supplier"
  >("none");
  const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(
    new Set()
  );

  // Загрузка данных
  const {
    data: suppliesData,
    loading,
    error,
    refetch,
  } = useQuery(GET_MY_SUPPLIES, {
    fetchPolicy: "cache-and-network",
    onError: (error) => {
      toast.error("Ошибка загрузки расходников: " + error.message);
    },
  });

  const supplies: Supply[] = suppliesData?.mySupplies || [];

  // Объединение идентичных расходников
  const consolidatedSupplies = useMemo(() => {
    const suppliesMap = new Map<string, Supply>();

    supplies.forEach((supply) => {
      const key = `${supply.name}-${supply.category}-${supply.supplier}`;

      if (suppliesMap.has(key)) {
        const existing = suppliesMap.get(key)!;
        // Суммируем количества
        existing.currentStock += supply.currentStock;
        existing.quantity += supply.quantity;
        // Берем максимальный минимальный остаток
        existing.minStock = Math.max(existing.minStock, supply.minStock);
        // Обновляем статус на основе суммарного остатка
        if (existing.currentStock === 0) {
          existing.status = "out-of-stock";
        } else if (existing.currentStock <= existing.minStock) {
          existing.status = "low-stock";
        } else {
          existing.status = "available";
        }
        // Обновляем дату на более позднюю
        if (new Date(supply.updatedAt) > new Date(existing.updatedAt)) {
          existing.updatedAt = supply.updatedAt;
        }
      } else {
        // Создаем копию с правильным статусом
        const consolidatedSupply = { ...supply };
        if (consolidatedSupply.currentStock === 0) {
          consolidatedSupply.status = "out-of-stock";
        } else if (
          consolidatedSupply.currentStock <= consolidatedSupply.minStock
        ) {
          consolidatedSupply.status = "low-stock";
        } else {
          consolidatedSupply.status = "available";
        }
        suppliesMap.set(key, consolidatedSupply);
      }
    });

    return Array.from(suppliesMap.values());
  }, [supplies]);

  // Статистика на основе объединенных данных
  const stats = useMemo(() => {
    const total = consolidatedSupplies.length;
    const available = consolidatedSupplies.filter(
      (s) => s.status === "available"
    ).length;
    const lowStock = consolidatedSupplies.filter(
      (s) => s.currentStock <= s.minStock && s.currentStock > 0
    ).length;
    const outOfStock = consolidatedSupplies.filter(
      (s) => s.currentStock === 0
    ).length;
    const inTransit = consolidatedSupplies.filter(
      (s) => s.status === "in-transit"
    ).length;
    const totalValue = consolidatedSupplies.reduce(
      (sum, s) => sum + s.price * s.currentStock,
      0
    );
    const categories = new Set(consolidatedSupplies.map((s) => s.category))
      .size;
    const suppliers = new Set(consolidatedSupplies.map((s) => s.supplier)).size;

    return {
      total,
      available,
      lowStock,
      outOfStock,
      inTransit,
      totalValue,
      categories,
      suppliers,
    };
  }, [consolidatedSupplies]);

  // Фильтрация и сортировка объединенных данных
  const filteredAndSortedSupplies = useMemo(() => {
    let filtered = consolidatedSupplies.filter((supply) => {
      const matchesSearch =
        supply.name.toLowerCase().includes(filters.search.toLowerCase()) ||
        supply.description
          .toLowerCase()
          .includes(filters.search.toLowerCase()) ||
        supply.supplier.toLowerCase().includes(filters.search.toLowerCase());

      const matchesCategory =
        !filters.category || supply.category === filters.category;
      const matchesStatus = !filters.status || supply.status === filters.status;
      const matchesSupplier =
        !filters.supplier || supply.supplier === filters.supplier;
      const matchesLowStock =
        !filters.lowStock || supply.currentStock <= supply.minStock;

      return (
        matchesSearch &&
        matchesCategory &&
        matchesStatus &&
        matchesSupplier &&
        matchesLowStock
      );
    });

    // Сортировка
    filtered.sort((a, b) => {
      const aValue = a[sort.field];
      const bValue = b[sort.field];

      if (typeof aValue === "string" && typeof bValue === "string") {
        return sort.direction === "asc"
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue);
      }

      if (typeof aValue === "number" && typeof bValue === "number") {
        return sort.direction === "asc" ? aValue - bValue : bValue - aValue;
      }

      return 0;
    });

    return filtered;
  }, [consolidatedSupplies, filters, sort]);

  // Уникальные значения для фильтров на основе объединенных данных
  const uniqueCategories = useMemo(
    () => [...new Set(consolidatedSupplies.map((s) => s.category))].sort(),
    [consolidatedSupplies]
  );
  const uniqueStatuses = useMemo(
    () => [...new Set(consolidatedSupplies.map((s) => s.status))].sort(),
    [consolidatedSupplies]
  );
  const uniqueSuppliers = useMemo(
    () => [...new Set(consolidatedSupplies.map((s) => s.supplier))].sort(),
    [consolidatedSupplies]
  );

  // Обработчики
  const handleSort = useCallback((field: keyof Supply) => {
    setSort((prev) => ({
      field,
      direction:
        prev.field === field && prev.direction === "asc" ? "desc" : "asc",
    }));
  }, []);

  const handleFilterChange = useCallback(
    (key: keyof FilterState, value: string | boolean) => {
      setFilters((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  const clearFilters = useCallback(() => {
    setFilters({
      search: "",
      category: "",
      status: "",
      supplier: "",
      lowStock: false,
    });
  }, []);

  // Получение всех поставок для конкретного расходника
  const getSupplyDeliveries = useCallback(
    (supply: Supply) => {
      const key = `${supply.name}-${supply.category}-${supply.supplier}`;
      return supplies.filter(
        (s) => `${s.name}-${s.category}-${s.supplier}` === key
      );
    },
    [supplies]
  );

  // Обработчик разворачивания/сворачивания расходника
  const toggleSupplyExpansion = useCallback((supplyId: string) => {
    setExpandedSupplies((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(supplyId)) {
        newSet.delete(supplyId);
      } else {
        newSet.add(supplyId);
      }
      return newSet;
    });
  }, []);

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat("ru-RU", {
      style: "currency",
      currency: "RUB",
    }).format(value);

  const formatNumber = (value: number) =>
    new Intl.NumberFormat("ru-RU").format(value);

  const getStatusConfig = (status: string) =>
    STATUS_CONFIG[status as keyof typeof STATUS_CONFIG] ||
    STATUS_CONFIG.available;

  // Группировка данных
  const groupedSupplies = useMemo(() => {
    if (groupBy === "none")
      return { "Все расходники": filteredAndSortedSupplies };

    const groups: Record<string, Supply[]> = {};

    filteredAndSortedSupplies.forEach((supply) => {
      const key = supply[groupBy] || "Не указано";
      if (!groups[key]) groups[key] = [];
      groups[key].push(supply);
    });

    return groups;
  }, [filteredAndSortedSupplies, groupBy]);

  // Экспорт данных
  const exportData = useCallback(
    (format: "csv" | "json") => {
      const data = filteredAndSortedSupplies.map((supply) => ({
        Название: supply.name,
        Описание: supply.description,
        Категория: supply.category,
        Статус: getStatusConfig(supply.status).label,
        "Остаток (шт)": supply.currentStock,
        "Мин. остаток (шт)": supply.minStock,
        "Цена (руб)": supply.price,
        Поставщик: supply.supplier,
        "Дата создания": new Date(supply.createdAt).toLocaleDateString("ru-RU"),
      }));

      if (format === "csv") {
        const csv = [
          Object.keys(data[0]).join(","),
          ...data.map((row) => Object.values(row).join(",")),
        ].join("\n");

        const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = `расходники_${
          new Date().toISOString().split("T")[0]
        }.csv`;
        link.click();
      } else {
        const json = JSON.stringify(data, null, 2);
        const blob = new Blob([json], { type: "application/json" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = `расходники_${
          new Date().toISOString().split("T")[0]
        }.json`;
        link.click();
      }

      toast.success(`Данные экспортированы в формате ${format.toUpperCase()}`);
    },
    [filteredAndSortedSupplies, getStatusConfig]
  );

  // Аналитические данные для графиков на основе объединенных данных
  const analyticsData = useMemo(() => {
    const categoryStats = uniqueCategories.map((category) => {
      const categorySupplies = consolidatedSupplies.filter(
        (s) => s.category === category
      );
      return {
        name: category,
        count: categorySupplies.length,
        value: categorySupplies.reduce(
          (sum, s) => sum + s.price * s.currentStock,
          0
        ),
        stock: categorySupplies.reduce((sum, s) => sum + s.currentStock, 0),
      };
    });

    const statusStats = uniqueStatuses.map((status) => {
      const statusSupplies = consolidatedSupplies.filter(
        (s) => s.status === status
      );
      return {
        name: getStatusConfig(status).label,
        count: statusSupplies.length,
        value: statusSupplies.reduce(
          (sum, s) => sum + s.price * s.currentStock,
          0
        ),
      };
    });

    const supplierStats = uniqueSuppliers.map((supplier) => {
      const supplierSupplies = consolidatedSupplies.filter(
        (s) => s.supplier === supplier
      );
      return {
        name: supplier,
        count: supplierSupplies.length,
        value: supplierSupplies.reduce(
          (sum, s) => sum + s.price * s.currentStock,
          0
        ),
      };
    });

    return { categoryStats, statusStats, supplierStats };
  }, [
    consolidatedSupplies,
    uniqueCategories,
    uniqueStatuses,
    uniqueSuppliers,
    getStatusConfig,
  ]);

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-smooth flex items-center justify-center">
        <Card className="p-6 bg-red-500/10 border-red-500/20">
          <div className="text-center">
            <AlertTriangle className="h-12 w-12 text-red-400 mx-auto mb-4" />
            <h2 className="text-xl font-bold text-white mb-2">
              Ошибка загрузки
            </h2>
            <p className="text-white/60 mb-4">{error.message}</p>
            <Button onClick={() => refetch()} variant="outline">
              Попробовать снова
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-smooth">
      <Sidebar />

      <main className={`transition-all duration-300 ${getSidebarMargin()}`}>
        <div className="p-6">
          {/* Хлебные крошки и заголовок */}
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => router.back()}
                className="text-white/70 hover:text-white hover:bg-white/10"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                Назад
              </Button>
              <div>
                <h1 className="text-2xl font-bold text-white flex items-center space-x-3">
                  <div className="p-2 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg">
                    <Wrench className="h-6 w-6 text-white" />
                  </div>
                  <span>Расходники фулфилмента</span>
                </h1>
                <p className="text-white/60 mt-1">
                  Управление расходными материалами и инвентарем
                </p>
              </div>
            </div>

            <div className="flex items-center space-x-3">
              {/* Переключатель режимов просмотра */}
              <div className="flex items-center bg-white/5 rounded-lg p-1">
                <Button
                  variant={viewMode === "grid" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setViewMode("grid")}
                  className={`h-8 px-3 ${
                    viewMode === "grid"
                      ? "bg-blue-500 text-white"
                      : "text-white/70 hover:text-white hover:bg-white/10"
                  }`}
                >
                  <Grid3X3 className="h-4 w-4" />
                </Button>
                <Button
                  variant={viewMode === "list" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setViewMode("list")}
                  className={`h-8 px-3 ${
                    viewMode === "list"
                      ? "bg-blue-500 text-white"
                      : "text-white/70 hover:text-white hover:bg-white/10"
                  }`}
                >
                  <List className="h-4 w-4" />
                </Button>
                <Button
                  variant={viewMode === "analytics" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setViewMode("analytics")}
                  className={`h-8 px-3 ${
                    viewMode === "analytics"
                      ? "bg-blue-500 text-white"
                      : "text-white/70 hover:text-white hover:bg-white/10"
                  }`}
                >
                  <BarChart3 className="h-4 w-4" />
                </Button>
              </div>

              {/* Группировка */}
              <select
                value={groupBy}
                onChange={(e) => setGroupBy(e.target.value as typeof groupBy)}
                className="bg-white/5 border border-white/20 rounded-md px-3 py-2 text-white text-sm"
              >
                <option value="none" className="bg-slate-800">
                  Без группировки
                </option>
                <option value="category" className="bg-slate-800">
                  По категориям
                </option>
                <option value="status" className="bg-slate-800">
                  По статусу
                </option>
                <option value="supplier" className="bg-slate-800">
                  По поставщикам
                </option>
              </select>

              {/* Экспорт */}
              <div className="relative group">
                <Button
                  variant="outline"
                  size="sm"
                  className="text-white border-white/20 hover:bg-white/10"
                >
                  <Download className="h-4 w-4 mr-2" />
                  Экспорт
                </Button>
                <div className="absolute right-0 top-full mt-2 w-48 bg-slate-800 border border-white/20 rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-10">
                  <div className="p-2 space-y-1">
                    <button
                      onClick={() => exportData("csv")}
                      className="w-full text-left px-3 py-2 text-sm text-white hover:bg-white/10 rounded flex items-center"
                    >
                      <FileSpreadsheet className="h-4 w-4 mr-2" />
                      Экспорт в CSV
                    </button>
                    <button
                      onClick={() => exportData("json")}
                      className="w-full text-left px-3 py-2 text-sm text-white hover:bg-white/10 rounded flex items-center"
                    >
                      <Hash className="h-4 w-4 mr-2" />
                      Экспорт в JSON
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Статистические карточки */}
          <div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-4 mb-6">
            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-blue-500/20 rounded-lg">
                  <Package className="h-4 w-4 text-blue-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Всего</p>
                  <p className="text-lg font-bold text-white">{stats.total}</p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-green-500/20 rounded-lg">
                  <CheckCircle className="h-4 w-4 text-green-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Доступно</p>
                  <p className="text-lg font-bold text-white">
                    {stats.available}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-yellow-500/20 rounded-lg">
                  <AlertTriangle className="h-4 w-4 text-yellow-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Мало</p>
                  <p className="text-lg font-bold text-white">
                    {stats.lowStock}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-red-500/20 rounded-lg">
                  <AlertTriangle className="h-4 w-4 text-red-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Нет в наличии</p>
                  <p className="text-lg font-bold text-white">
                    {stats.outOfStock}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-purple-500/20 rounded-lg">
                  <Clock className="h-4 w-4 text-purple-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">В пути</p>
                  <p className="text-lg font-bold text-white">
                    {stats.inTransit}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-emerald-500/20 rounded-lg">
                  <DollarSign className="h-4 w-4 text-emerald-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Стоимость</p>
                  <p className="text-sm font-bold text-white">
                    {formatCurrency(stats.totalValue)}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-orange-500/20 rounded-lg">
                  <Layers className="h-4 w-4 text-orange-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Категории</p>
                  <p className="text-lg font-bold text-white">
                    {stats.categories}
                  </p>
                </div>
              </div>
            </Card>

            <Card className="glass-card p-4">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-pink-500/20 rounded-lg">
                  <User className="h-4 w-4 text-pink-300" />
                </div>
                <div>
                  <p className="text-xs text-white/60">Поставщики</p>
                  <p className="text-lg font-bold text-white">
                    {stats.suppliers}
                  </p>
                </div>
              </div>
            </Card>
          </div>

          {/* Панель фильтров и поиска */}
          <Card className="glass-card p-4 mb-6">
            <div className="flex flex-col space-y-4">
              {/* Основная строка поиска и кнопок */}
              <div className="flex items-center space-x-4">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
                  <Input
                    placeholder="Поиск по названию, описанию или поставщику..."
                    value={filters.search}
                    onChange={(e) =>
                      handleFilterChange("search", e.target.value)
                    }
                    className="pl-10 bg-white/5 border-white/10 text-white placeholder:text-white/40"
                  />
                </div>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowFilters(!showFilters)}
                  className="text-white border-white/20 hover:bg-white/10"
                >
                  <Filter className="h-4 w-4 mr-2" />
                  Фильтры
                  {(filters.category ||
                    filters.status ||
                    filters.supplier ||
                    filters.lowStock) && (
                    <Badge className="ml-2 bg-blue-500/20 text-blue-300">
                      Активны
                    </Badge>
                  )}
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={clearFilters}
                  className="text-white border-white/20 hover:bg-white/10"
                >
                  Очистить
                </Button>
              </div>

              {/* Расширенные фильтры */}
              {showFilters && (
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4 pt-4 border-t border-white/10">
                  <div>
                    <label className="block text-xs font-medium text-white/70 mb-2">
                      Категория
                    </label>
                    <select
                      value={filters.category}
                      onChange={(e) =>
                        handleFilterChange("category", e.target.value)
                      }
                      className="w-full bg-white/5 border border-white/10 rounded-md px-3 py-2 text-white text-sm"
                    >
                      <option value="">Все категории</option>
                      {uniqueCategories.map((category) => (
                        <option
                          key={category}
                          value={category}
                          className="bg-slate-800"
                        >
                          {category}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-white/70 mb-2">
                      Статус
                    </label>
                    <select
                      value={filters.status}
                      onChange={(e) =>
                        handleFilterChange("status", e.target.value)
                      }
                      className="w-full bg-white/5 border border-white/10 rounded-md px-3 py-2 text-white text-sm"
                    >
                      <option value="">Все статусы</option>
                      {uniqueStatuses.map((status) => (
                        <option
                          key={status}
                          value={status}
                          className="bg-slate-800"
                        >
                          {getStatusConfig(status).label}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-white/70 mb-2">
                      Поставщик
                    </label>
                    <select
                      value={filters.supplier}
                      onChange={(e) =>
                        handleFilterChange("supplier", e.target.value)
                      }
                      className="w-full bg-white/5 border border-white/10 rounded-md px-3 py-2 text-white text-sm"
                    >
                      <option value="">Все поставщики</option>
                      {uniqueSuppliers.map((supplier) => (
                        <option
                          key={supplier}
                          value={supplier}
                          className="bg-slate-800"
                        >
                          {supplier}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="flex items-end">
                    <label className="flex items-center space-x-2 text-sm text-white">
                      <input
                        type="checkbox"
                        checked={filters.lowStock}
                        onChange={(e) =>
                          handleFilterChange("lowStock", e.target.checked)
                        }
                        className="rounded border-white/20 bg-white/5 text-blue-500 focus:ring-blue-500/20"
                      />
                      <span>Только с низким остатком</span>
                    </label>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {/* Заголовки сортировки для списочного вида */}
          {viewMode === "list" && (
            <Card className="glass-card p-4 mb-4">
              <div className="grid grid-cols-8 gap-4 text-xs font-medium text-white/70 uppercase tracking-wider">
                <button
                  onClick={() => handleSort("name")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Название</span>
                  {sort.field === "name" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("category")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Категория</span>
                  {sort.field === "category" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("status")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Статус</span>
                  {sort.field === "status" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("currentStock")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Остаток</span>
                  {sort.field === "currentStock" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("minStock")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Мин. остаток</span>
                  {sort.field === "minStock" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("price")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Цена</span>
                  {sort.field === "price" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <button
                  onClick={() => handleSort("supplier")}
                  className="text-left flex items-center space-x-1 hover:text-white"
                >
                  <span>Поставщик</span>
                  {sort.field === "supplier" &&
                    (sort.direction === "asc" ? (
                      <SortAsc className="h-3 w-3" />
                    ) : (
                      <SortDesc className="h-3 w-3" />
                    ))}
                </button>
                <span>Действия</span>
              </div>
            </Card>
          )}

          {/* Список расходников */}
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {Array.from({ length: 8 }).map((_, i) => (
                <Card key={i} className="glass-card p-4 animate-pulse">
                  <div className="h-4 bg-white/10 rounded mb-2"></div>
                  <div className="h-3 bg-white/5 rounded mb-4"></div>
                  <div className="space-y-2">
                    <div className="h-2 bg-white/5 rounded"></div>
                    <div className="h-2 bg-white/5 rounded w-2/3"></div>
                  </div>
                </Card>
              ))}
            </div>
          ) : filteredAndSortedSupplies.length === 0 ? (
            <Card className="glass-card p-8 text-center">
              <Package className="h-12 w-12 text-white/40 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-white mb-2">
                Расходники не найдены
              </h3>
              <p className="text-white/60">
                Попробуйте изменить параметры поиска или фильтрации
              </p>
            </Card>
          ) : viewMode === "analytics" ? (
            // Аналитический режим с графиками
            <div className="space-y-6">
              {/* Графики аналитики */}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Распределение по категориям */}
                <Card className="glass-card p-6">
                  <div className="flex items-center space-x-3 mb-4">
                    <div className="p-2 bg-blue-500/20 rounded-lg">
                      <PieChart className="h-5 w-5 text-blue-300" />
                    </div>
                    <h3 className="text-lg font-semibold text-white">
                      По категориям
                    </h3>
                  </div>
                  <div className="space-y-3">
                    {analyticsData.categoryStats.map((item, index) => {
                      const colors = [
                        "bg-blue-500",
                        "bg-green-500",
                        "bg-yellow-500",
                        "bg-purple-500",
                        "bg-pink-500",
                      ];
                      const color = colors[index % colors.length];
                      const percentage =
                        stats.total > 0 ? (item.count / stats.total) * 100 : 0;

                      return (
                        <div key={item.name} className="space-y-2">
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-white/80">{item.name}</span>
                            <span className="text-white font-medium">
                              {item.count}
                            </span>
                          </div>
                          <div className="w-full bg-white/10 rounded-full h-2">
                            <div
                              className={`h-2 rounded-full ${color} transition-all`}
                              style={{ width: `${percentage}%` }}
                            ></div>
                          </div>
                          <div className="flex items-center justify-between text-xs text-white/60">
                            <span>{percentage.toFixed(1)}%</span>
                            <span>{formatCurrency(item.value)}</span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </Card>

                {/* Распределение по статусам */}
                <Card className="glass-card p-6">
                  <div className="flex items-center space-x-3 mb-4">
                    <div className="p-2 bg-green-500/20 rounded-lg">
                      <Target className="h-5 w-5 text-green-300" />
                    </div>
                    <h3 className="text-lg font-semibold text-white">
                      По статусам
                    </h3>
                  </div>
                  <div className="space-y-3">
                    {analyticsData.statusStats.map((item, index) => {
                      const colors = [
                        "bg-green-500",
                        "bg-yellow-500",
                        "bg-red-500",
                        "bg-blue-500",
                        "bg-purple-500",
                      ];
                      const color = colors[index % colors.length];
                      const percentage =
                        stats.total > 0 ? (item.count / stats.total) * 100 : 0;

                      return (
                        <div key={item.name} className="space-y-2">
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-white/80">{item.name}</span>
                            <span className="text-white font-medium">
                              {item.count}
                            </span>
                          </div>
                          <div className="w-full bg-white/10 rounded-full h-2">
                            <div
                              className={`h-2 rounded-full ${color} transition-all`}
                              style={{ width: `${percentage}%` }}
                            ></div>
                          </div>
                          <div className="flex items-center justify-between text-xs text-white/60">
                            <span>{percentage.toFixed(1)}%</span>
                            <span>{formatCurrency(item.value)}</span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </Card>

                {/* ТОП поставщики */}
                <Card className="glass-card p-6">
                  <div className="flex items-center space-x-3 mb-4">
                    <div className="p-2 bg-purple-500/20 rounded-lg">
                      <Sparkles className="h-5 w-5 text-purple-300" />
                    </div>
                    <h3 className="text-lg font-semibold text-white">
                      ТОП поставщики
                    </h3>
                  </div>
                  <div className="space-y-3">
                    {analyticsData.supplierStats
                      .sort((a, b) => b.value - a.value)
                      .slice(0, 5)
                      .map((item, index) => {
                        const colors = [
                          "bg-gold-500",
                          "bg-silver-500",
                          "bg-bronze-500",
                          "bg-blue-500",
                          "bg-green-500",
                        ];
                        const color = colors[index] || "bg-gray-500";
                        const maxValue = Math.max(
                          ...analyticsData.supplierStats.map((s) => s.value)
                        );
                        const percentage =
                          maxValue > 0 ? (item.value / maxValue) * 100 : 0;

                        return (
                          <div key={item.name} className="space-y-2">
                            <div className="flex items-center justify-between text-sm">
                              <div className="flex items-center space-x-2">
                                <span className="text-xs font-bold text-yellow-400">
                                  #{index + 1}
                                </span>
                                <span
                                  className="text-white/80 truncate max-w-32"
                                  title={item.name}
                                >
                                  {item.name}
                                </span>
                              </div>
                              <span className="text-white font-medium">
                                {item.count}
                              </span>
                            </div>
                            <div className="w-full bg-white/10 rounded-full h-2">
                              <div
                                className={`h-2 rounded-full bg-gradient-to-r from-yellow-500 to-orange-500 transition-all`}
                                style={{ width: `${percentage}%` }}
                              ></div>
                            </div>
                            <div className="flex items-center justify-between text-xs text-white/60">
                              <span>{formatCurrency(item.value)}</span>
                            </div>
                          </div>
                        );
                      })}
                  </div>
                </Card>
              </div>

              {/* Дополнительные метрики */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <Card className="glass-card p-4">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-emerald-500/20 rounded-lg">
                      <Zap className="h-4 w-4 text-emerald-300" />
                    </div>
                    <div>
                      <p className="text-xs text-white/60">Средняя цена</p>
                      <p className="text-lg font-bold text-white">
                        {consolidatedSupplies.length > 0
                          ? formatCurrency(
                              consolidatedSupplies.reduce(
                                (sum, s) => sum + s.price,
                                0
                              ) / consolidatedSupplies.length
                            )
                          : "0 ₽"}
                      </p>
                    </div>
                  </div>
                </Card>

                <Card className="glass-card p-4">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-indigo-500/20 rounded-lg">
                      <Activity className="h-4 w-4 text-indigo-300" />
                    </div>
                    <div>
                      <p className="text-xs text-white/60">Средний остаток</p>
                      <p className="text-lg font-bold text-white">
                        {consolidatedSupplies.length > 0
                          ? Math.round(
                              consolidatedSupplies.reduce(
                                (sum, s) => sum + s.currentStock,
                                0
                              ) / consolidatedSupplies.length
                            )
                          : 0}
                      </p>
                    </div>
                  </div>
                </Card>

                <Card className="glass-card p-4">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-rose-500/20 rounded-lg">
                      <AlertTriangle className="h-4 w-4 text-rose-300" />
                    </div>
                    <div>
                      <p className="text-xs text-white/60">
                        Критический остаток
                      </p>
                      <p className="text-lg font-bold text-white">
                        {
                          consolidatedSupplies.filter(
                            (s) => s.currentStock === 0
                          ).length
                        }
                      </p>
                    </div>
                  </div>
                </Card>

                <Card className="glass-card p-4">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-cyan-500/20 rounded-lg">
                      <TrendingUp className="h-4 w-4 text-cyan-300" />
                    </div>
                    <div>
                      <p className="text-xs text-white/60">Оборачиваемость</p>
                      <p className="text-lg font-bold text-white">
                        {((stats.available / stats.total) * 100).toFixed(1)}%
                      </p>
                    </div>
                  </div>
                </Card>
              </div>
            </div>
          ) : groupBy !== "none" ? (
            // Группированный вид
            <div className="space-y-6">
              {Object.entries(groupedSupplies).map(
                ([groupName, groupSupplies]) => (
                  <Card key={groupName} className="glass-card">
                    <div className="p-4 border-b border-white/10">
                      <div className="flex items-center justify-between">
                        <h3 className="text-lg font-semibold text-white flex items-center space-x-2">
                          <Layers className="h-5 w-5" />
                          <span>{groupName}</span>
                          <Badge className="bg-blue-500/20 text-blue-300">
                            {groupSupplies.length}
                          </Badge>
                        </h3>
                        <div className="text-sm text-white/60">
                          Общая стоимость:{" "}
                          {formatCurrency(
                            groupSupplies.reduce(
                              (sum, s) => sum + s.price * s.currentStock,
                              0
                            )
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="p-4">
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                        {groupSupplies.map((supply) => {
                          const statusConfig = getStatusConfig(supply.status);
                          const StatusIcon = statusConfig.icon;
                          const isLowStock =
                            supply.currentStock <= supply.minStock &&
                            supply.currentStock > 0;
                          const stockPercentage =
                            supply.minStock > 0
                              ? (supply.currentStock / supply.minStock) * 100
                              : 100;

                          return (
                            <div key={supply.id}>
                              <Card
                              className="bg-white/5 border-white/10 p-3 hover:bg-white/10 transition-all duration-300 cursor-pointer"
                              onClick={() => toggleSupplyExpansion(supply.id)}
                            >
                              <div className="flex items-start justify-between mb-2">
                                <div className="flex-1 flex items-start space-x-2">
                                  <div className="flex items-center justify-center w-4 h-4 mt-0.5">
                                    {expandedSupplies.has(supply.id) ? (
                                      <ChevronDown className="h-3 w-3 text-white/60" />
                                    ) : (
                                      <ChevronRight className="h-3 w-3 text-white/60" />
                                    )}
                                  </div>
                                  <div className="flex-1">
                                    <h4 className="font-medium text-white text-sm mb-1">
                                      {supply.name}
                                    </h4>
                                    <p className="text-xs text-white/60 line-clamp-1">
                                      {supply.description}
                                    </p>
                                  </div>
                                </div>
                                <div className="flex items-center space-x-2">
                                  <Badge className="bg-blue-500/20 text-blue-300 text-xs">
                                    {getSupplyDeliveries(supply).length}
                                  </Badge>
                                  <Badge
                                    className={`${statusConfig.color} text-xs`}
                                  >
                                    <StatusIcon className="h-3 w-3 mr-1" />
                                    {statusConfig.label}
                                  </Badge>
                                </div>
                              </div>

                              <div className="space-y-1 text-xs">
                                <div className="flex items-center justify-between">
                                  <span className="text-white/60">
                                    Остаток:
                                  </span>
                                  <span
                                    className={`font-medium ${
                                      isLowStock
                                        ? "text-yellow-300"
                                        : "text-white"
                                    }`}
                                  >
                                    {formatNumber(supply.currentStock)}{" "}
                                    {supply.unit}
                                  </span>
                                </div>
                                <div className="w-full bg-white/10 rounded-full h-1">
                                  <div
                                    className={`h-1 rounded-full transition-all ${
                                      stockPercentage <= 50
                                        ? "bg-red-500"
                                        : stockPercentage <= 100
                                        ? "bg-yellow-500"
                                        : "bg-green-500"
                                    }`}
                                    style={{
                                      width: `${Math.min(
                                        stockPercentage,
                                        100
                                      )}%`,
                                    }}
                                  ></div>
                                </div>
                                <div className="flex items-center justify-between">
                                  <span className="text-white/60">Цена:</span>
                                  <span className="text-white font-medium">
                                    {formatCurrency(supply.price)}
                                  </span>
                                </div>
                              </div>
                            </Card>

                            {/* Развернутые поставки для группированного режима */}
                            {expandedSupplies.has(supply.id) && (
                              <div className="ml-6 mt-2 space-y-2">
                                <div className="text-xs font-medium text-white/70 uppercase tracking-wider mb-2 flex items-center space-x-2">
                                  <Truck className="h-3 w-3" />
                                  <span>Поставки</span>
                                </div>
                                
                                {getSupplyDeliveries(supply).map((delivery, deliveryIndex) => {
                                  const deliveryStatusConfig = getStatusConfig(delivery.status);
                                  const DeliveryStatusIcon = deliveryStatusConfig.icon;
                                  
                                  return (
                                    <Card key={`${delivery.id}-${deliveryIndex}`} className="bg-white/10 border-white/20 p-2">
                                      <div className="flex items-center justify-between text-xs">
                                        <div className="flex items-center space-x-2">
                                          <Badge className={`${deliveryStatusConfig.color} text-xs`}>
                                            <DeliveryStatusIcon className="h-3 w-3 mr-1" />
                                            {deliveryStatusConfig.label}
                                          </Badge>
                                          <span className="text-white/60">
                                            {new Date(delivery.createdAt).toLocaleDateString("ru-RU", {
                                              month: "short",
                                              day: "numeric"
                                            })}
                                          </span>
                                        </div>
                                        <div className="flex items-center space-x-4">
                                          <span className="text-white">
                                            {formatNumber(delivery.currentStock)} {delivery.unit}
                                          </span>
                                          <span className="text-white font-medium">
                                            {formatCurrency(delivery.price * delivery.currentStock)}
                                          </span>
                                        </div>
                                      </div>
                                    </Card>
                                  );
                                })}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                  </Card>
                )
              )}
            </div>
          ) : viewMode === "grid" ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">                const statusConfig = getStatusConfig(supply.status);
                const StatusIcon = statusConfig.icon;
                const isLowStock =
                  supply.currentStock <= supply.minStock &&
                  supply.currentStock > 0;
                const stockPercentage =
                  supply.minStock > 0
                    ? (supply.currentStock / supply.minStock) * 100
                    : 100;

                return (
                  <div key={supply.id}>
                    {/* Основная карточка расходника */}
                    <Card
                      className="glass-card p-4 hover:bg-white/15 transition-all duration-300 cursor-pointer group"
                      onClick={() => toggleSupplyExpansion(supply.id)}
                    >
                      {/* Заголовок карточки */}
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex-1 flex items-start space-x-2">
                          <div className="flex items-center justify-center w-5 h-5 mt-0.5">
                            {expandedSupplies.has(supply.id) ? (
                              <ChevronDown className="h-4 w-4 text-white/60" />
                            ) : (
                              <ChevronRight className="h-4 w-4 text-white/60" />
                            )}
                          </div>
                          <div className="flex-1">
                            <h3 className="font-semibold text-white text-sm mb-1 group-hover:text-blue-300 transition-colors">
                              {supply.name}
                            </h3>
                            <p className="text-xs text-white/60 line-clamp-2">
                              {supply.description}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Badge className="bg-blue-500/20 text-blue-300 text-xs">
                            {getSupplyDeliveries(supply).length} поставок
                          </Badge>
                          <Badge className={`${statusConfig.color} text-xs`}>
                            <StatusIcon className="h-3 w-3 mr-1" />
                            {statusConfig.label}
                          </Badge>
                        </div>
                      </div>

                      {/* Статистика остатков */}
                      <div className="space-y-2 mb-3">
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-white/60">Остаток:</span>
                          <span
                            className={`font-medium ${
                              isLowStock ? "text-yellow-300" : "text-white"
                            }`}
                          >
                            {formatNumber(supply.currentStock)} {supply.unit}
                          </span>
                        </div>

                        {/* Прогресс-бар остатков */}
                        <div className="w-full bg-white/10 rounded-full h-1.5">
                          <div
                            className={`h-1.5 rounded-full transition-all ${
                              stockPercentage <= 50
                                ? "bg-red-500"
                                : stockPercentage <= 100
                                ? "bg-yellow-500"
                                : "bg-green-500"
                            }`}
                            style={{
                              width: `${Math.min(stockPercentage, 100)}%`,
                            }}
                          ></div>
                        </div>

                        <div className="flex items-center justify-between text-xs">
                          <span className="text-white/60">Мин. остаток:</span>
                          <span className="text-white/80">
                            {formatNumber(supply.minStock)} {supply.unit}
                          </span>
                        </div>
                      </div>

                      {/* Дополнительная информация */}
                      <div className="space-y-1 mb-3 text-xs">
                        <div className="flex items-center justify-between">
                          <span className="text-white/60">Категория:</span>
                          <Badge
                            variant="outline"
                            className="text-xs border-white/20 text-white/80"
                          >
                            {supply.category}
                          </Badge>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-white/60">Цена:</span>
                          <span className="text-white font-medium">
                            {formatCurrency(supply.price)}
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-white/60">Поставщик:</span>
                          <span
                            className="text-white/80 truncate max-w-24"
                            title={supply.supplier}
                          >
                            {supply.supplier}
                          </span>
                        </div>
                      </div>

                      {/* Действия */}
                      <div className="flex items-center space-x-2 pt-2 border-t border-white/10">
                        <Button
                          size="sm"
                          variant="ghost"
                          className="flex-1 text-xs text-white/70 hover:text-white hover:bg-white/10"
                        >
                          <Eye className="h-3 w-3 mr-1" />
                          Подробнее
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-xs text-white/70 hover:text-white hover:bg-white/10"
                        >
                          <Activity className="h-3 w-3" />
                        </Button>
                      </div>
                    </Card>

                    {/* Развернутые поставки */}
                    {expandedSupplies.has(supply.id) && (
                      <div className="mt-2 space-y-2">
                        <div className="text-xs font-medium text-white/70 uppercase tracking-wider mb-3 flex items-center space-x-2">
                          <Truck className="h-3 w-3" />
                          <span>История поставок</span>
                        </div>

                        {getSupplyDeliveries(supply).map(
                          (delivery, deliveryIndex) => {
                            const deliveryStatusConfig = getStatusConfig(
                              delivery.status
                            );
                            const DeliveryStatusIcon =
                              deliveryStatusConfig.icon;

                            return (
                              <Card
                                key={`${delivery.id}-${deliveryIndex}`}
                                className="bg-white/5 border-white/10 p-3"
                              >
                                <div className="flex items-start justify-between">
                                  <div className="flex-1">
                                    <div className="flex items-center space-x-3 mb-2">
                                      <Badge
                                        className={`${deliveryStatusConfig.color} text-xs`}
                                      >
                                        <DeliveryStatusIcon className="h-3 w-3 mr-1" />
                                        {deliveryStatusConfig.label}
                                      </Badge>
                                      <span className="text-xs text-white/60">
                                        {new Date(
                                          delivery.createdAt
                                        ).toLocaleDateString("ru-RU", {
                                          year: "numeric",
                                          month: "short",
                                          day: "numeric",
                                          hour: "2-digit",
                                          minute: "2-digit",
                                        })}
                                      </span>
                                    </div>

                                    <div className="grid grid-cols-2 gap-3 text-xs">
                                      <div>
                                        <p className="text-white/60">Остаток</p>
                                        <p className="text-white font-medium">
                                          {formatNumber(delivery.currentStock)}{" "}
                                          {delivery.unit}
                                        </p>
                                      </div>
                                      <div>
                                        <p className="text-white/60">
                                          Заказано
                                        </p>
                                        <p className="text-white font-medium">
                                          {formatNumber(delivery.quantity)}{" "}
                                          {delivery.unit}
                                        </p>
                                      </div>
                                      <div>
                                        <p className="text-white/60">Цена</p>
                                        <p className="text-white font-medium">
                                          {formatCurrency(delivery.price)}
                                        </p>
                                      </div>
                                      <div>
                                        <p className="text-white/60">
                                          Стоимость
                                        </p>
                                        <p className="text-white font-medium">
                                          {formatCurrency(
                                            delivery.price *
                                              delivery.currentStock
                                          )}
                                        </p>
                                      </div>
                                    </div>

                                    {delivery.description &&
                                      delivery.description !==
                                        supply.description && (
                                        <div className="mt-2">
                                          <p className="text-white/60 text-xs">
                                            Описание
                                          </p>
                                          <p className="text-white/80 text-xs">
                                            {delivery.description}
                                          </p>
                                        </div>
                                      )}
                                  </div>
                                </div>
                              </Card>
                            );
                          }
                        )}

                        {/* Итоговая статистика по поставкам */}
                        <Card className="bg-gradient-to-r from-blue-500/10 to-purple-500/10 border-blue-500/20 p-3 mt-3">
                          <div className="grid grid-cols-2 gap-3 text-xs">
                            <div>
                              <p className="text-white/60">Всего поставок</p>
                              <p className="text-white font-bold">
                                {getSupplyDeliveries(supply).length}
                              </p>
                            </div>
                            <div>
                              <p className="text-white/60">Общая стоимость</p>
                              <p className="text-white font-bold">
                                {formatCurrency(
                                  getSupplyDeliveries(supply).reduce(
                                    (sum, d) => sum + d.price * d.currentStock,
                                    0
                                  )
                                )}
                              </p>
                            </div>
                          </div>
                        </Card>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          ) : (
            // Списочный вид
            <div className="space-y-2">
              {filteredAndSortedSupplies.map((supply) => {
                const statusConfig = getStatusConfig(supply.status);
                const StatusIcon = statusConfig.icon;
                const isLowStock =
                  supply.currentStock <= supply.minStock &&
                  supply.currentStock > 0;

                return (
                  <div key={supply.id}>
                    <Card
                      className="glass-card p-4 hover:bg-white/15 transition-all duration-300 cursor-pointer"
                      onClick={() => toggleSupplyExpansion(supply.id)}
                    >
                                          <div className="grid grid-cols-8 gap-4 items-center text-sm">
                        <div className="flex items-center space-x-2">
                          <div className="flex items-center justify-center w-4 h-4">
                            {expandedSupplies.has(supply.id) ? (
                              <ChevronDown className="h-3 w-3 text-white/60" />
                            ) : (
                              <ChevronRight className="h-3 w-3 text-white/60" />
                            )}
                          </div>
                          <div>
                            <p className="font-medium text-white">{supply.name}</p>
                            <p className="text-xs text-white/60 truncate">
                              {supply.description}
                            </p>
                          </div>
                        </div>

                                              <div className="flex items-center space-x-2">
                          <Badge
                            variant="outline"
                            className="text-xs border-white/20 text-white/80"
                          >
                            {supply.category}
                          </Badge>
                        </div>

                        <div className="flex items-center space-x-2">
                          <Badge className="bg-blue-500/20 text-blue-300 text-xs">
                            {getSupplyDeliveries(supply).length}
                          </Badge>
                          <Badge className={`${statusConfig.color} text-xs`}>
                            <StatusIcon className="h-3 w-3 mr-1" />
                            {statusConfig.label}
                          </Badge>
                        </div>

                      <div
                        className={`font-medium ${
                          isLowStock ? "text-yellow-300" : "text-white"
                        }`}
                      >
                        {formatNumber(supply.currentStock)} {supply.unit}
                      </div>

                      <div className="text-white/80">
                        {formatNumber(supply.minStock)} {supply.unit}
                      </div>

                      <div className="font-medium text-white">
                        {formatCurrency(supply.price)}
                      </div>

                      <div
                        className="text-white/80 truncate"
                        title={supply.supplier}
                      >
                        {supply.supplier}
                      </div>

                      <div className="flex items-center space-x-2">
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-xs text-white/70 hover:text-white hover:bg-white/10"
                        >
                          <Eye className="h-3 w-3" />
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-xs text-white/70 hover:text-white hover:bg-white/10"
                        >
                          <Activity className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                    </Card>

                    {/* Развернутые поставки для списочного режима */}
                    {expandedSupplies.has(supply.id) && (
                      <div className="ml-6 mt-2 space-y-2">
                        <div className="text-xs font-medium text-white/70 uppercase tracking-wider mb-3 flex items-center space-x-2">
                          <Truck className="h-3 w-3" />
                          <span>История поставок</span>
                        </div>
                        
                        {getSupplyDeliveries(supply).map((delivery, deliveryIndex) => {
                          const deliveryStatusConfig = getStatusConfig(delivery.status);
                          const DeliveryStatusIcon = deliveryStatusConfig.icon;
                          
                          return (
                            <Card key={`${delivery.id}-${deliveryIndex}`} className="bg-white/5 border-white/10 p-3">
                              <div className="grid grid-cols-6 gap-4 items-center text-xs">
                                <div className="flex items-center space-x-2">
                                  <Badge className={`${deliveryStatusConfig.color} text-xs`}>
                                    <DeliveryStatusIcon className="h-3 w-3 mr-1" />
                                    {deliveryStatusConfig.label}
                                  </Badge>
                                </div>
                                
                                <div>
                                  <p className="text-white/60">Дата</p>
                                  <p className="text-white font-medium">
                                    {new Date(delivery.createdAt).toLocaleDateString("ru-RU", {
                                      month: "short",
                                      day: "numeric",
                                      hour: "2-digit",
                                      minute: "2-digit"
                                    })}
                                  </p>
                                </div>
                                
                                <div>
                                  <p className="text-white/60">Остаток</p>
                                  <p className="text-white font-medium">
                                    {formatNumber(delivery.currentStock)} {delivery.unit}
                                  </p>
                                </div>
                                
                                <div>
                                  <p className="text-white/60">Заказано</p>
                                  <p className="text-white font-medium">
                                    {formatNumber(delivery.quantity)} {delivery.unit}
                                  </p>
                                </div>
                                
                                <div>
                                  <p className="text-white/60">Цена</p>
                                  <p className="text-white font-medium">
                                    {formatCurrency(delivery.price)}
                                  </p>
                                </div>
                                
                                <div>
                                  <p className="text-white/60">Стоимость</p>
                                  <p className="text-white font-medium">
                                    {formatCurrency(delivery.price * delivery.currentStock)}
                                  </p>
                                </div>
                              </div>
                              
                              {delivery.description && delivery.description !== supply.description && (
                                <div className="mt-2 pt-2 border-t border-white/10">
                                  <p className="text-white/60 text-xs">Описание: {delivery.description}</p>
                                </div>
                              )}
                            </Card>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}

          {/* Пагинация (если нужна) */}
          {filteredAndSortedSupplies.length > 0 && (
            <div className="mt-6 flex items-center justify-between">
              <p className="text-sm text-white/60">
                Показано {filteredAndSortedSupplies.length} из{" "}
                {consolidatedSupplies.length} расходников (объединено из{" "}
                {supplies.length} записей)
              </p>
            </div>
          )}
        </div>
      </main>


    </div>
  );
}
