"use client";

import { FormEvent, useMemo, useState } from "react";
import {
  PageHeader,
  StatCard,
  Panel,
  AdminButton,
  StatusBadge,
  FilterBar,
  SearchInput,
  SelectFilter,
  EmptyState,
} from "@/components/admin/ui";
import { formatCurrency, lowStockThreshold } from "@/components/admin/adminNav";
import { useStore } from "@/context/StoreContext";

type MovementType = "purchase" | "sale" | "return" | "adjustment";

type InventoryLog = {
  id: string;
  product: string;
  sku: string;
  change: number;
  note: string;
  type: MovementType;
  date: string;
};

const inputClass =
  "w-full rounded-lg border border-border bg-white px-3 py-2 text-sm outline-none focus:border-accent";

export default function AdminInventoryPage() {
  const { store } = useStore();
  const [search, setSearch] = useState("");
  const [stockFilter, setStockFilter] = useState("all");
  const [productId, setProductId] = useState("");
  const [movementType, setMovementType] = useState<MovementType>("purchase");
  const [quantity, setQuantity] = useState(1);
  const [note, setNote] = useState("");
  const [logs, setLogs] = useState<InventoryLog[]>([]);

  const metrics = useMemo(() => {
    const products = store.products;
    return {
      total: products.length,
      low: products.filter((p) => p.stock > 0 && p.stock <= lowStockThreshold).length,
      out: products.filter((p) => p.stock <= 0).length,
      value: products.reduce((sum, p) => sum + p.cost_price * Math.max(p.stock, 0), 0),
    };
  }, [store.products]);

  const demoLogs = useMemo(() => {
    const fromProducts: InventoryLog[] = store.products.slice(0, 6).map((p, i) => ({
      id: `LOG-P-${p.id}`,
      product: p.name,
      sku: p.sku,
      change: i % 2 === 0 ? 20 : -2,
      note: i % 2 === 0 ? "+20 Added by Admin" : "-2 Sold",
      type: i % 2 === 0 ? "purchase" : "sale",
      date: new Date(Date.now() - i * 86400000).toISOString().slice(0, 10),
    }));
    const samples: InventoryLog[] = [
      {
        id: "LOG-S-1",
        product: "Demo Refrigerator",
        sku: "DEMO-RF-01",
        change: 15,
        note: "+15 Purchase received",
        type: "purchase",
        date: new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10),
      },
      {
        id: "LOG-S-2",
        product: "Demo Washing Machine",
        sku: "DEMO-WM-01",
        change: -1,
        note: "-1 Return to supplier",
        type: "return",
        date: new Date(Date.now() - 3 * 86400000).toISOString().slice(0, 10),
      },
      {
        id: "LOG-S-3",
        product: "Demo Microwave",
        sku: "DEMO-MW-01",
        change: 3,
        note: "+3 Manual adjustment",
        type: "adjustment",
        date: new Date(Date.now() - 4 * 86400000).toISOString().slice(0, 10),
      },
    ];
    return [...logs, ...fromProducts, ...samples];
  }, [store.products, logs]);

  const filteredProducts = useMemo(() => {
    return store.products.filter((p) => {
      const q = search.toLowerCase();
      const matchesSearch =
        !q ||
        p.name.toLowerCase().includes(q) ||
        p.sku.toLowerCase().includes(q);
      const matchesStock =
        stockFilter === "all" ||
        (stockFilter === "low" && p.stock > 0 && p.stock <= lowStockThreshold) ||
        (stockFilter === "out" && p.stock <= 0) ||
        (stockFilter === "in" && p.stock > lowStockThreshold);
      return matchesSearch && matchesStock;
    });
  }, [store.products, search, stockFilter]);

  const handleMovement = (e: FormEvent) => {
    e.preventDefault();
    const product = store.products.find((p) => p.id === productId);
    if (!product || quantity <= 0) return;

    const signed =
      movementType === "sale" ? -Math.abs(quantity) : Math.abs(quantity);
    const labels: Record<MovementType, string> = {
      purchase: `+${Math.abs(quantity)} Purchase received`,
      sale: `-${Math.abs(quantity)} Sold`,
      return: `+${Math.abs(quantity)} Customer return`,
      adjustment: `${signed > 0 ? "+" : ""}${signed} Manual adjustment`,
    };

    setLogs((prev) => [
      {
        id: `LOG-${Date.now()}`,
        product: product.name,
        sku: product.sku,
        change: movementType === "return" ? Math.abs(quantity) : signed,
        note: note || labels[movementType],
        type: movementType,
        date: new Date().toISOString().slice(0, 10),
      },
      ...prev,
    ]);
    setNote("");
    setQuantity(1);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Inventory"
        description="Track stock levels, record movements, and review inventory logs."
        actions={<AdminButton href="/admin/products">Manage Products</AdminButton>}
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Total SKUs" value={metrics.total} />
        <StatCard label="Low Stock" value={metrics.low} tone="warning" hint={`≤ ${lowStockThreshold} units`} />
        <StatCard label="Out of Stock" value={metrics.out} tone="danger" />
        <StatCard label="Stock Value" value={formatCurrency(metrics.value)} tone="info" />
      </div>

      <div className="grid gap-4 xl:grid-cols-3">
        <Panel title="Stock Movement" description="Purchase, sale, return, or manual adjustment" className="xl:col-span-1">
          <form onSubmit={handleMovement} className="space-y-3">
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Product</label>
              <select
                className={inputClass}
                value={productId}
                onChange={(e) => setProductId(e.target.value)}
                required
              >
                <option value="">Select product</option>
                {store.products.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name} ({p.stock} in stock)
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Type</label>
              <select
                className={inputClass}
                value={movementType}
                onChange={(e) => setMovementType(e.target.value as MovementType)}
              >
                <option value="purchase">Purchase</option>
                <option value="sale">Sale</option>
                <option value="return">Return</option>
                <option value="adjustment">Manual Adjustment</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Quantity</label>
              <input
                type="number"
                min={1}
                className={inputClass}
                value={quantity}
                onChange={(e) => setQuantity(Number(e.target.value))}
                required
              />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Note</label>
              <input
                className={inputClass}
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="Optional note"
              />
            </div>
            <AdminButton type="submit">Record Movement</AdminButton>
          </form>
        </Panel>

        <Panel title="Stock Levels" description="Current inventory by product" className="xl:col-span-2">
          <FilterBar>
            <SearchInput value={search} onChange={setSearch} placeholder="Search name or SKU…" />
            <SelectFilter
              value={stockFilter}
              onChange={setStockFilter}
              options={[
                { value: "all", label: "All stock" },
                { value: "in", label: "In stock" },
                { value: "low", label: "Low stock" },
                { value: "out", label: "Out of stock" },
              ]}
            />
          </FilterBar>
          {filteredProducts.length === 0 ? (
            <EmptyState title="No products found" description="Adjust filters or add products first." />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[560px] text-left text-sm">
                <thead>
                  <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                    <th className="pb-2 font-semibold">Product</th>
                    <th className="pb-2 font-semibold">SKU</th>
                    <th className="pb-2 font-semibold">Stock</th>
                    <th className="pb-2 font-semibold">Status</th>
                    <th className="pb-2 font-semibold">Value</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredProducts.map((p) => {
                    const status =
                      p.stock <= 0 ? "Out of stock" : p.stock <= lowStockThreshold ? "Low" : "In stock";
                    return (
                      <tr key={p.id} className="border-b border-border/60">
                        <td className="py-3 font-medium">{p.name}</td>
                        <td className="py-3 text-muted-foreground">{p.sku}</td>
                        <td className="py-3">{p.stock}</td>
                        <td className="py-3">
                          <StatusBadge status={status === "In stock" ? "active" : status === "Low" ? "pending" : "failed"} />
                        </td>
                        <td className="py-3">{formatCurrency(p.cost_price * Math.max(p.stock, 0))}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </Panel>
      </div>

      <Panel title="Inventory Logs" description="Recent stock movements and demo entries">
        {demoLogs.length === 0 ? (
          <EmptyState title="No logs yet" description="Record a stock movement to see activity here." />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[640px] text-left text-sm">
              <thead>
                <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                  <th className="pb-2 font-semibold">Date</th>
                  <th className="pb-2 font-semibold">Product</th>
                  <th className="pb-2 font-semibold">SKU</th>
                  <th className="pb-2 font-semibold">Change</th>
                  <th className="pb-2 font-semibold">Type</th>
                  <th className="pb-2 font-semibold">Note</th>
                </tr>
              </thead>
              <tbody>
                {demoLogs.map((log) => (
                  <tr key={log.id} className="border-b border-border/60">
                    <td className="py-3 text-muted-foreground">{log.date}</td>
                    <td className="py-3 font-medium">{log.product}</td>
                    <td className="py-3 text-muted-foreground">{log.sku}</td>
                    <td className={`py-3 font-semibold ${log.change >= 0 ? "text-emerald-600" : "text-red-600"}`}>
                      {log.change >= 0 ? `+${log.change}` : log.change}
                    </td>
                    <td className="py-3 capitalize">{log.type}</td>
                    <td className="py-3 text-muted-foreground">{log.note}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>
    </div>
  );
}
