/** فهرست محصولات */
import Link from "next/link";
import { z } from "zod";
import { AdminHeader, Card, Empty, Pill, Table } from "@/components/admin/ui";
import { SubmitButton } from "@/components/admin/SubmitButton";
import { ProductVisual } from "@/components/product/ProductVisual";
import { Icon } from "@/components/ui/Icon";
import { db } from "@/lib/db";
import { faNumber, formatToman } from "@/lib/format";
import { normalizeFa } from "@/lib/persian";
import { toggleProductAction } from "@/server/admin/products";
import type { ProductShape } from "@/types/catalog";
import { requireStaffPage } from "@/server/admin/guard";

export const metadata = { title: "محصولات" };
export const dynamic = "force-dynamic";

export default async function AdminProducts({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
  await requireStaffPage("/admin/products", "products");
  const q = z.string().trim().max(60).optional().catch(undefined).parse((await searchParams).q);
  const tokens = q ? normalizeFa(q).split(" ").filter(Boolean) : [];
  const products = await db.product.findMany({
    where: tokens.length ? { AND: tokens.map((t) => ({ searchText: { contains: t } })) } : {},
    orderBy: { id: "desc" },
    take: 100,
    include: { brand: { select: { name: true, nameEn: true } }, category: { select: { name: true } }, variants: { select: { stock: true, isActive: true } }, images: { select: { url: true, alt: true }, orderBy: { sortOrder: "asc" }, take: 1 } },
  });

  return (
    <>
      <AdminHeader
        title="محصولات"
        description={`${faNumber(products.length)} محصول`}
        actions={<Link href="/admin/products/new" className="btn-primary h-10 px-4"><Icon name="plus" size={16} /> محصول جدید</Link>}
      />
      <Card>
        <form className="mb-4 flex gap-2">
          <input name="q" defaultValue={q} placeholder="جستجوی نام، برند یا دسته" className="field h-10 max-w-xs" />
          <button className="btn-outline h-10 px-4">جستجو</button>
        </form>
        {products.length ? (
          <Table head={["محصول", "دسته", "قیمت از", "موجودی", "وضعیت", ""]}>
            {products.map((p) => {
              const stock = p.variants.filter((v) => v.isActive).reduce((s, v) => s + v.stock, 0);
              return (
                <tr key={p.id}>
                  <td>
                    <Link href={`/admin/products/${p.id}`} className="flex items-center gap-3 hover:underline">
                      <span className="size-11 shrink-0 overflow-hidden rounded-lg bg-mist"><ProductVisual image={p.images[0]} sizes="44px" shape={p.shape as ProductShape} tone={p.tone} label={p.brand.nameEn} className="size-full" /></span>
                      <span><span className="block text-xs font-bold">{p.brand.name}</span>{p.name}</span>
                    </Link>
                  </td>
                  <td className="text-xs text-muted">{p.category.name}</td>
                  <td className="whitespace-nowrap">{formatToman(p.minPrice)}</td>
                  <td className={stock === 0 ? "text-muted" : ""}>{faNumber(stock)} <span className="text-xs text-muted">({faNumber(p.variants.length)} تنوع)</span></td>
                  <td><Pill tone={p.isActive ? "ink" : "line"}>{p.isActive ? "فعال" : "مخفی"}</Pill></td>
                  <td>
                    <form action={toggleProductAction}>
                      <input type="hidden" name="id" value={p.id} />
                      <SubmitButton className="text-xs underline" pendingText="…">{p.isActive ? "مخفی کن" : "فعال کن"}</SubmitButton>
                    </form>
                  </td>
                </tr>
              );
            })}
          </Table>
        ) : <Empty>محصولی پیدا نشد</Empty>}
      </Card>
    </>
  );
}
