import type { Metadata } from "next";
import Link from "next/link";
import { ShoppingBag, Tags } from "lucide-react";
import { Button } from "@/components/Button";
import {
  listProductsForAdmin,
  listCategoriesForAdmin,
  formatPrice,
} from "@/lib/store/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  KpiCard,
  ConfirmButton,
  type Column,
} from "@/components/admin";
import {
  createProduct,
  createCategory,
  renameCategory,
  deleteCategory,
} from "./actions";

export const metadata: Metadata = { title: "Store" };
export const dynamic = "force-dynamic";

type Product = Awaited<ReturnType<typeof listProductsForAdmin>>[number];

const STATUS_FILTERS = ["all", "draft", "published", "archived"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];
function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}

export default async function AdminStorePage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; q?: string }>;
}) {
  const params = await searchParams;
  const statusFilter: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const [products, categories] = await Promise.all([
    listProductsForAdmin(),
    listCategoriesForAdmin(),
  ]);

  const counts = products.reduce<Record<string, number>>((acc, p) => {
    acc[p.status] = (acc[p.status] ?? 0) + 1;
    return acc;
  }, {});
  const inStock = products.filter((p) => p.stockStatus === "in_stock").length;

  let filtered = products;
  if (statusFilter !== "all") filtered = filtered.filter((p) => p.status === statusFilter);
  if (query) {
    filtered = filtered.filter((p) =>
      [p.title, p.slug, p.shortDescription].join(" ").toLowerCase().includes(query),
    );
  }

  const buildHref = (status: StatusFilter) => {
    const parts: string[] = [];
    if (status !== "all") parts.push(`status=${status}`);
    if (query) parts.push(`q=${encodeURIComponent(query)}`);
    return `/admin/store${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  const columns: Column<Product>[] = [
    {
      key: "title",
      header: "Product",
      cell: (p) => (
        <div className="min-w-0">
          <Link
            href={`/admin/store/${p.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {p.title}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">{p.slug}</div>
        </div>
      ),
    },
    {
      key: "price",
      header: "Price",
      cell: (p) => (
        <span className="font-mono text-[13px] text-[var(--color-ink)]">
          {formatPrice(p.priceMinor, p.currency)}
        </span>
      ),
    },
    {
      key: "stock",
      header: "Stock",
      cell: (p) => (
        <StatusBadge
          label={p.stockStatus.replace("_", "-")}
          tone={
            p.stockStatus === "in_stock"
              ? "success"
              : p.stockStatus === "out_of_stock"
                ? "danger"
                : "muted"
          }
          dot
        />
      ),
    },
    {
      key: "status",
      header: "Status",
      cell: (p) => <StatusBadge label={p.status} dot />,
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (p) => (
        <Link
          href={`/admin/store/${p.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Edit →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Commerce"
        title="Store"
        lede="Products and categories for the members' store."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total products" value={products.length} Icon={ShoppingBag} tone="ink" />
        <KpiCard label="Published" value={counts.published ?? 0} tone="emerald" />
        <KpiCard label="In stock" value={inStock} tone="blue" />
        <KpiCard label="Categories" value={categories.length} Icon={Tags} tone="slate" />
      </div>

      <div className="mb-6 grid gap-6 lg:grid-cols-2">
        <FormSection title="Categories" description="Rename or delete existing, or add a new one below.">
          <form
            action={createCategory}
            className="grid gap-3 md:grid-cols-[1fr_auto]"
          >
            <InputField
              name="name"
              placeholder="Category name"
              required
              maxLength={120}
            />
            <div className="flex items-end">
              <Button type="submit" variant="secondary" className="!px-4 !py-2 !text-[13px]">
                Add
              </Button>
            </div>
          </form>
          {categories.length > 0 && (
            <ul className="mt-4 space-y-2">
              {categories.map((c) => (
                <li
                  key={c.id}
                  className="flex flex-wrap items-center gap-2 rounded-lg border border-[var(--color-line)] bg-[var(--color-line)]/20 p-2"
                >
                  <form
                    action={renameCategory}
                    className="flex flex-1 flex-wrap items-center gap-2"
                  >
                    <input type="hidden" name="id" value={c.id} />
                    <input
                      name="name"
                      type="text"
                      required
                      maxLength={120}
                      defaultValue={c.name}
                      className="min-w-[120px] flex-1 rounded-md border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px]"
                    />
                    <input
                      name="description"
                      type="text"
                      maxLength={500}
                      defaultValue={c.description}
                      placeholder="Description"
                      className="min-w-[180px] flex-[2] rounded-md border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px]"
                    />
                    <button
                      type="submit"
                      className="rounded-lg bg-white px-3 py-1.5 text-[12px] font-semibold text-[var(--color-ink)] ring-1 ring-[var(--color-line)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                    >
                      Save
                    </button>
                  </form>
                  <form action={deleteCategory}>
                    <input type="hidden" name="id" value={c.id} />
                    <ConfirmButton
                      label="Delete"
                      confirmLabel="Confirm?"
                      tone="danger"
                      className="!px-3 !py-1.5 !text-[12px]"
                    />
                  </form>
                </li>
              ))}
            </ul>
          )}
        </FormSection>

        <FormSection title="New product">
          <form action={createProduct} className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Title"
              name="title"
              required
              minLength={3}
              maxLength={200}
              wrapClassName="md:col-span-2"
            />
            <SelectField label="Category" name="categoryId">
              <option value="">— none —</option>
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </SelectField>
            <InputField
              label="Price (minor units, e.g. pence)"
              name="priceMinor"
              type="number"
              min={0}
              max={1_000_000}
              defaultValue={0}
            />
            <TextareaField
              label="Short description"
              name="shortDescription"
              rows={2}
              maxLength={400}
              wrapClassName="md:col-span-2"
            />
            <div className="md:col-span-2">
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create product
              </Button>
            </div>
          </form>
        </FormSection>
      </div>

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/store">
              {statusFilter !== "all" && <input type="hidden" name="status" value={statusFilter} />}
              <SearchInput defaultValue={params.q ?? ""} placeholder="Search title, slug…" />
            </form>
          }
        >
          {STATUS_FILTERS.map((s) => (
            <FilterPill
              key={s}
              href={buildHref(s)}
              label={s}
              count={s === "all" ? products.length : counts[s] ?? 0}
              active={statusFilter === s}
            />
          ))}
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={ShoppingBag}
          title="No products match"
          description="Create a new product above or clear filters."
        />
      ) : (
        <DataTable columns={columns} rows={filtered} rowKey={(p) => p.id} />
      )}
    </>
  );
}
