"use client";

import { useEffect, useState } from "react";
import { Warehouse, Search, AlertTriangle, CheckCircle, Package } from "lucide-react";

interface Product {
  id: number;
  name: string;
  sku: string;
  categoryName: string | null;
  fabric: string | null;
  color: string | null;
  costPrice: string;
  sellingPrice: string;
  stock: number;
  lowStockThreshold: number;
  isActive: boolean;
}

function formatCurrency(val: string | number) {
  const num = typeof val === "string" ? parseFloat(val) : val;
  return "৳" + new Intl.NumberFormat("bn-BD", { maximumFractionDigits: 0 }).format(num);
}

export default function InventoryPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<"all" | "low" | "ok">("all");

  useEffect(() => {
    fetch("/api/products")
      .then((r) => r.json())
      .then(setProducts)
      .finally(() => setLoading(false));
  }, []);

  const filtered = products.filter((p) => {
    const matchSearch =
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      p.sku.toLowerCase().includes(search.toLowerCase());
    if (filter === "low") return matchSearch && p.stock <= p.lowStockThreshold;
    if (filter === "ok") return matchSearch && p.stock > p.lowStockThreshold;
    return matchSearch;
  });

  const totalStockValue = products.reduce((sum, p) => sum + p.stock * parseFloat(p.costPrice), 0);
  const totalRetailValue = products.reduce((sum, p) => sum + p.stock * parseFloat(p.sellingPrice), 0);
  const lowStockCount = products.filter((p) => p.stock <= p.lowStockThreshold).length;
  const totalItems = products.reduce((sum, p) => sum + p.stock, 0);

  if (loading) {
    return <div className="flex items-center justify-center h-96"><div className="animate-spin w-10 h-10 border-4 border-brand-500 border-t-transparent rounded-full" /></div>;
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-3">
          <Warehouse className="text-brand-500" size={28} />
          Inventory
        </h1>
        <p className="text-gray-500 mt-1">Track your saree stock levels</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-5 mb-6">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
          <p className="text-sm text-gray-500">Total Items</p>
          <p className="text-2xl font-bold text-gray-900">{totalItems}</p>
          <p className="text-xs text-gray-400">{products.length} products</p>
        </div>
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
          <p className="text-sm text-gray-500">Stock Value (Cost)</p>
          <p className="text-2xl font-bold text-blue-600">{formatCurrency(totalStockValue)}</p>
        </div>
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
          <p className="text-sm text-gray-500">Retail Value</p>
          <p className="text-2xl font-bold text-green-600">{formatCurrency(totalRetailValue)}</p>
        </div>
        <div className="bg-white rounded-2xl shadow-sm border border-orange-200 p-5">
          <p className="text-sm text-orange-600">Low Stock Items</p>
          <p className="text-2xl font-bold text-orange-600">{lowStockCount}</p>
          <p className="text-xs text-orange-400">Need restocking</p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-6">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="relative flex-1">
            <Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
            <input type="text" placeholder="Search by name or SKU..." value={search} onChange={(e) => setSearch(e.target.value)} className="w-full pl-10 pr-4 py-2.5 bg-gray-50 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
          </div>
          <div className="flex gap-2">
            {(["all", "low", "ok"] as const).map((f) => (
              <button key={f} onClick={() => setFilter(f)} className={`px-4 py-2 rounded-xl text-sm font-medium transition-colors ${filter === f ? "bg-brand-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
                {f === "all" ? "All" : f === "low" ? "⚠ Low Stock" : "✓ In Stock"}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Inventory Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Product</th>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">SKU</th>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Category</th>
                <th className="text-center py-4 px-4 font-semibold text-gray-600">Stock</th>
                <th className="text-center py-4 px-4 font-semibold text-gray-600">Threshold</th>
                <th className="text-right py-4 px-4 font-semibold text-gray-600">Cost Value</th>
                <th className="text-right py-4 px-4 font-semibold text-gray-600">Retail Value</th>
                <th className="text-center py-4 px-4 font-semibold text-gray-600">Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p) => {
                const isLow = p.stock <= p.lowStockThreshold;
                return (
                  <tr key={p.id} className={`border-b border-gray-50 hover:bg-gray-50/50 ${isLow ? "bg-red-50/30" : ""}`}>
                    <td className="py-3 px-4">
                      <p className="font-medium text-gray-900">{p.name}</p>
                      <div className="flex gap-1.5 mt-0.5">
                        {p.fabric && <span className="text-xs text-gray-400">{p.fabric}</span>}
                        {p.color && <span className="text-xs text-gray-400">• {p.color}</span>}
                      </div>
                    </td>
                    <td className="py-3 px-4 text-gray-500 font-mono text-xs">{p.sku}</td>
                    <td className="py-3 px-4">
                      {p.categoryName && <span className="px-2 py-0.5 bg-brand-50 text-brand-700 text-xs rounded-full">{p.categoryName}</span>}
                    </td>
                    <td className="py-3 px-4 text-center">
                      <span className={`text-lg font-bold ${isLow ? "text-red-600" : "text-green-600"}`}>{p.stock}</span>
                    </td>
                    <td className="py-3 px-4 text-center text-gray-400">{p.lowStockThreshold}</td>
                    <td className="py-3 px-4 text-right text-gray-600">{formatCurrency(p.stock * parseFloat(p.costPrice))}</td>
                    <td className="py-3 px-4 text-right font-medium text-gray-900">{formatCurrency(p.stock * parseFloat(p.sellingPrice))}</td>
                    <td className="py-3 px-4 text-center">
                      {isLow ? (
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-red-100 text-red-700 text-xs rounded-full font-medium">
                          <AlertTriangle size={12} /> Low
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-green-100 text-green-700 text-xs rounded-full font-medium">
                          <CheckCircle size={12} /> OK
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
