"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { DataTable, PageHeader } from "@/components/admin/page-header";
import { apiFetch } from "@/lib/admin-api";
import { formatCurrency } from "@/lib/utils";

type Product = {
  id: string;
  name: string;
  sku: string;
  price: number;
  stock: number;
  status: string;
  type: string;
  category?: { name: string } | null;
};

export default function AdminProductsPage() {
  const [items, setItems] = useState<Product[]>([]);
  const [error, setError] = useState("");
  const [q, setQ] = useState("");

  async function load(search = q) {
    try {
      const data = await apiFetch<{ items: Product[] }>(
        `/api/products?admin=1&limit=50${search ? `&q=${encodeURIComponent(search)}` : ""}`,
      );
      setItems(data.items);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load");
    }
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function remove(id: string) {
    if (!confirm("Delete this product?")) return;
    await apiFetch(`/api/products/${id}`, { method: "DELETE" });
    await load();
  }

  return (
    <div>
      <PageHeader
        title="Products"
        description="Manage catalog items"
        actions={
          <>
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && load()}
              placeholder="Search…"
              className="h-11 rounded-xl border border-border bg-bg px-3 text-sm outline-none focus:border-accent"
            />
            <Button type="button" variant="secondary" onClick={() => load()}>
              Search
            </Button>
            <Button href="/admin/products/new">New product</Button>
          </>
        }
      />
      {error ? <p className="mb-4 text-danger">{error}</p> : null}
      <DataTable
        columns={[
          { key: "name", label: "Name" },
          { key: "sku", label: "SKU" },
          { key: "category", label: "Category" },
          { key: "price", label: "Price" },
          { key: "stock", label: "Stock" },
          { key: "status", label: "Status" },
          { key: "actions", label: "", className: "text-right" },
        ]}
        rows={items.map((p) => ({
          id: p.id,
          name: (
            <div>
              <p className="font-medium">{p.name}</p>
              <p className="text-xs text-muted">{p.type}</p>
            </div>
          ),
          sku: p.sku,
          category: p.category?.name || "—",
          price: formatCurrency(p.price),
          stock: p.stock,
          status: p.status,
          actions: (
            <div className="flex justify-end gap-2">
              <Link href={`/admin/products/${p.id}/edit`} className="text-accent hover:underline">
                Edit
              </Link>
              <button onClick={() => remove(p.id)} className="text-danger hover:underline">
                Delete
              </button>
            </div>
          ),
        }))}
        empty="No products yet"
      />
    </div>
  );
}
