"use client";

import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Wrench,
  Plus,
  Search,
  TrendingUp,
  AlertCircle,
  Eye,
} from "lucide-react";

// Мок данные для расходников селлеров
const mockSellerMaterials = [
  {
    id: "1",
    materialName: "Пакеты полиэтиленовые 30х40",
    seller: "PackStore LLC",
    category: "Упаковка",
    quantity: 10000,
    expectedDate: "2024-01-14",
    status: "planned",
    unitPrice: 2.5,
    totalValue: 25000,
    purpose: "Упаковка мелких товаров",
  },
  {
    id: "2",
    materialName: "Скотч упаковочный прозрачный",
    seller: "Packaging Pro",
    category: "Упаковка",
    quantity: 500,
    expectedDate: "2024-01-11",
    status: "in-transit",
    unitPrice: 85,
    totalValue: 42500,
    purpose: "Заклейка коробок",
  },
  {
    id: "3",
    materialName: "Этикетки штрих-код 58х40",
    seller: "LabelTech",
    category: "Маркировка",
    quantity: 50000,
    expectedDate: "2024-01-09",
    status: "delivered",
    unitPrice: 0.8,
    totalValue: 40000,
    purpose: "Маркировка товаров",
  },
];

export function SellerMaterialsTab() {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  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 getStatusBadge = (status: string) => {
    const statusConfig = {
      planned: {
        color: "text-blue-300 border-blue-400/30",
        label: "Запланировано",
      },
      "in-transit": {
        color: "text-yellow-300 border-yellow-400/30",
        label: "В пути",
      },
      delivered: {
        color: "text-green-300 border-green-400/30",
        label: "Доставлено",
      },
      "in-processing": {
        color: "text-purple-300 border-purple-400/30",
        label: "Обрабатывается",
      },
    };

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

    return (
      <Badge variant="outline" className={`glass-secondary ${config.color}`}>
        {config.label}
      </Badge>
    );
  };

  const filteredMaterials = mockSellerMaterials.filter((material) => {
    const matchesSearch =
      material.materialName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      material.seller.toLowerCase().includes(searchTerm.toLowerCase()) ||
      material.category.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesStatus =
      statusFilter === "all" || material.status === statusFilter;

    return matchesSearch && matchesStatus;
  });

  const getTotalValue = () => {
    return filteredMaterials.reduce(
      (sum, material) => sum + material.totalValue,
      0
    );
  };

  const getTotalQuantity = () => {
    return filteredMaterials.reduce(
      (sum, material) => sum + material.quantity,
      0
    );
  };

  return (
    <div className="h-full flex flex-col space-y-4 p-4">
      {/* Статистика с кнопкой */}
      <div className="flex items-center justify-between gap-4">
        <div className="grid grid-cols-2 lg:grid-cols-3 gap-3 flex-1">
          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-orange-500/20 rounded">
                <Wrench className="h-3 w-3 text-orange-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Поставок</p>
                <p className="text-lg font-bold text-white">
                  {filteredMaterials.length}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-green-500/20 rounded">
                <TrendingUp className="h-3 w-3 text-green-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Стоимость</p>
                <p className="text-lg font-bold text-white">
                  {formatCurrency(getTotalValue())}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-purple-500/20 rounded">
                <AlertCircle className="h-3 w-3 text-purple-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Единиц</p>
                <p className="text-lg font-bold text-white">
                  {getTotalQuantity().toLocaleString()}
                </p>
              </div>
            </div>
          </Card>
        </div>

        <Button
          size="sm"
          className="bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white text-sm px-6 h-[60px] whitespace-nowrap"
        >
          <Plus className="h-4 w-4 mr-2" />
          Заказать материалы
        </Button>
      </div>

      {/* Фильтры */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
          <Input
            placeholder="Поиск по материалам, селлерам..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="glass-input pl-10 text-white placeholder:text-white/40"
          />
        </div>

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="glass-input text-white text-sm px-3 py-2 rounded-lg bg-white/5 border border-white/10"
        >
          <option value="all">Все статусы</option>
          <option value="planned">Запланировано</option>
          <option value="in-transit">В пути</option>
          <option value="delivered">Доставлено</option>
          <option value="in-processing">Обрабатывается</option>
        </select>
      </div>

      {/* Список материалов */}
      <div className="flex-1 overflow-hidden">
        <div className="h-full overflow-y-auto space-y-3">
          {filteredMaterials.map((material) => (
            <Card
              key={material.id}
              className="glass-card p-4 hover:bg-white/10 transition-colors"
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-white font-medium">
                      {material.materialName}
                    </h3>
                    {getStatusBadge(material.status)}
                  </div>

                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
                    <div>
                      <p className="text-white/60">Селлер</p>
                      <p className="text-white">{material.seller}</p>
                    </div>
                    <div>
                      <p className="text-white/60">Категория</p>
                      <p className="text-white">{material.category}</p>
                    </div>
                    <div>
                      <p className="text-white/60">Количество</p>
                      <p className="text-white font-semibold">
                        {material.quantity.toLocaleString()} шт.
                      </p>
                    </div>
                    <div>
                      <p className="text-white/60">Ожидается</p>
                      <p className="text-white">
                        {formatDate(material.expectedDate)}
                      </p>
                    </div>
                  </div>

                  <div className="mt-3 flex items-center justify-between">
                    <div className="flex items-center gap-4 text-sm">
                      <span className="text-white/60">
                        Цена за ед.:{" "}
                        <span className="text-white">
                          {formatCurrency(material.unitPrice)}
                        </span>
                      </span>
                      <span className="text-white/60">
                        Общая стоимость:{" "}
                        <span className="text-green-400 font-semibold">
                          {formatCurrency(material.totalValue)}
                        </span>
                      </span>
                    </div>
                  </div>

                  <div className="mt-2">
                    <p className="text-white/60 text-xs">
                      Назначение:{" "}
                      <span className="text-white/80">{material.purpose}</span>
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2 ml-4">
                  <Button
                    size="sm"
                    variant="ghost"
                    className="text-white/60 hover:text-white hover:bg-white/10"
                  >
                    <Eye className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}
