"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 {
  Package,
  Plus,
  Search,
  TrendingUp,
  AlertCircle,
  Eye,
  Calendar,
  Package2,
  Box,
} from "lucide-react";

// Мок данные для поставок на Ozon
const mockOzonSupplies = [
  {
    id: "1",
    supplyId: "OZ-SP-240113-001",
    warehouse: "Тверь",
    deliveryDate: "2024-01-16",
    status: "awaiting_packaging",
    totalItems: 120,
    totalBoxes: 10,
    estimatedValue: 380000,
    products: [
      { name: "Телефон Samsung A54", quantity: 40, price: 6500 },
      { name: "Чехол силиконовый", quantity: 80, price: 850 },
    ],
  },
  {
    id: "2",
    supplyId: "OZ-SP-240112-002",
    warehouse: "Казань",
    deliveryDate: "2024-01-15",
    status: "sent_to_delivery",
    totalItems: 75,
    totalBoxes: 6,
    estimatedValue: 295000,
    products: [
      { name: "Наушники беспроводные", quantity: 25, price: 4200 },
      { name: "Зарядное устройство", quantity: 50, price: 1800 },
    ],
  },
  {
    id: "3",
    supplyId: "OZ-SP-240111-003",
    warehouse: "Екатеринбург",
    deliveryDate: "2024-01-14",
    status: "delivered",
    totalItems: 180,
    totalBoxes: 14,
    estimatedValue: 520000,
    products: [
      { name: "Планшет Xiaomi Pad", quantity: 60, price: 4800 },
      { name: "Клавиатура беспроводная", quantity: 120, price: 1650 },
    ],
  },
];

export function OzonSuppliesTab() {
  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 = {
      awaiting_packaging: {
        color: "text-blue-300 border-blue-400/30",
        label: "Ожидает упаковки",
      },
      sent_to_delivery: {
        color: "text-yellow-300 border-yellow-400/30",
        label: "Отправлена",
      },
      delivered: {
        color: "text-green-300 border-green-400/30",
        label: "Доставлена",
      },
      cancelled: { color: "text-red-300 border-red-400/30", label: "Отменена" },
      arbitration: {
        color: "text-orange-300 border-orange-400/30",
        label: "Арбитраж",
      },
    };

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

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

  const filteredSupplies = mockOzonSupplies.filter((supply) => {
    const matchesSearch =
      supply.supplyId.toLowerCase().includes(searchTerm.toLowerCase()) ||
      supply.warehouse.toLowerCase().includes(searchTerm.toLowerCase()) ||
      supply.products.some((p) =>
        p.name.toLowerCase().includes(searchTerm.toLowerCase())
      );

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

    return matchesSearch && matchesStatus;
  });

  const getTotalValue = () => {
    return filteredSupplies.reduce(
      (sum, supply) => sum + supply.estimatedValue,
      0
    );
  };

  const getTotalItems = () => {
    return filteredSupplies.reduce((sum, supply) => sum + supply.totalItems, 0);
  };

  const getTotalBoxes = () => {
    return filteredSupplies.reduce((sum, supply) => sum + supply.totalBoxes, 0);
  };

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

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

          <Card className="glass-card p-2 xl:p-3 h-[50px] xl:h-[60px]">
            <div className="flex items-center space-x-1.5 xl:space-x-2 h-full">
              <div className="p-1 xl:p-1.5 bg-purple-500/20 rounded">
                <Package2 className="h-2.5 w-2.5 xl:h-3 xl:w-3 text-purple-400" />
              </div>
              <div>
                <p className="text-white/60 text-[10px] xl:text-xs">Товаров</p>
                <p className="text-sm xl:text-lg font-bold text-white">
                  {getTotalItems()}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-2 xl:p-3 h-[50px] xl:h-[60px]">
            <div className="flex items-center space-x-1.5 xl:space-x-2 h-full">
              <div className="p-1 xl:p-1.5 bg-orange-500/20 rounded">
                <Box className="h-2.5 w-2.5 xl:h-3 xl:w-3 text-orange-400" />
              </div>
              <div>
                <p className="text-white/60 text-[10px] xl:text-xs">Коробок</p>
                <p className="text-sm xl:text-lg font-bold text-white">
                  {getTotalBoxes()}
                </p>
              </div>
            </div>
          </Card>
        </div>

        <Button
          size="sm"
          className="bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white text-xs xl:text-sm px-3 xl:px-6 h-[50px] xl:h-[60px] whitespace-nowrap w-full xl:w-auto"
        >
          <Plus className="h-3 w-3 xl:h-4 xl:w-4 mr-1 xl:mr-2" />
          <span className="hidden sm:inline">Создать поставку</span>
          <span className="sm:hidden">Создать</span>
        </Button>
      </div>

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

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="glass-input text-white text-xs xl:text-sm px-2 xl:px-3 py-1.5 xl:py-2 rounded-lg bg-white/5 border border-white/10 h-8 xl:h-auto"
        >
          <option value="all">Все статусы</option>
          <option value="created">Создана</option>
          <option value="confirmed">Подтверждена</option>
          <option value="in-transit">В пути</option>
          <option value="delivered">Доставлена</option>
          <option value="accepted">Принята</option>
        </select>
      </div>

      {/* Список поставок */}
      <div className="flex-1 overflow-hidden">
        <div className="h-full overflow-y-auto space-y-2 xl:space-y-3">
          {filteredSupplies.map((supply) => (
            <Card
              key={supply.id}
              className="glass-card p-2 xl: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-3">
                    <div className="w-6 h-6 bg-blue-500 rounded flex items-center justify-center">
                      <span className="text-white text-xs font-bold">O</span>
                    </div>
                    <h3 className="text-white font-medium">
                      {supply.supplyId}
                    </h3>
                    {getStatusBadge(supply.status)}
                  </div>

                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm mb-3">
                    <div>
                      <p className="text-white/60">Склад Ozon</p>
                      <p className="text-white">{supply.warehouse}</p>
                    </div>
                    <div>
                      <p className="text-white/60">Дата доставки</p>
                      <p className="text-white flex items-center gap-1">
                        <Calendar className="h-3 w-3" />
                        {formatDate(supply.deliveryDate)}
                      </p>
                    </div>
                    <div>
                      <p className="text-white/60">Товаров / Коробок</p>
                      <p className="text-white font-semibold">
                        {supply.totalItems} / {supply.totalBoxes}
                      </p>
                    </div>
                    <div>
                      <p className="text-white/60">Стоимость</p>
                      <p className="text-green-400 font-semibold">
                        {formatCurrency(supply.estimatedValue)}
                      </p>
                    </div>
                  </div>

                  {/* Список товаров в поставке */}
                  <div className="bg-white/5 rounded-lg p-3">
                    <p className="text-white/80 text-xs mb-2">
                      Товары в поставке:
                    </p>
                    <div className="space-y-1">
                      {supply.products.map((product, index) => (
                        <div
                          key={index}
                          className="flex items-center justify-between text-xs"
                        >
                          <span className="text-white/70">{product.name}</span>
                          <span className="text-white/60">
                            {product.quantity} шт. ×{" "}
                            {formatCurrency(product.price)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </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>
  );
}
