import Link from "next/link";
import { and, asc, eq, ilike, or } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { products, productGroups } from "@/db/schema";
import { formatVnd } from "@/lib/format";
import { PageHeader, TableWrap, EmptyState } from "@/components/ui";

export const dynamic = "force-dynamic";

/**
 * Bảng giá sản phẩm — mọi vai trò xem được (NVKD cần tra khi báo giá và lên đơn). Chỉ hiển thị,
 * không sửa ở đây: danh mục sản phẩm do quản lý cập nhật bằng nhập Excel.
 */
export default async function ProductListPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; nhom?: string }>;
}) {
  const session = await requireSession();
  const raw = await searchParams;
  // Nhóm là uuid do người dùng gõ trên đường dẫn: sai định dạng thì bỏ qua (nếu đưa thẳng vào truy vấn, Postgres báo lỗi → trang 500).
  const params = {
    q: (raw.q ?? "").trim().slice(0, 100),
    nhom: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw.nhom ?? "") ? raw.nhom : "",
  };

  const [groups, rows] = await Promise.all([
    db
      .select({ id: productGroups.id, name: productGroups.name })
      .from(productGroups)
      .where(eq(productGroups.tenantId, session.tenantId))
      .orderBy(asc(productGroups.name)),
    db
      .select({
        id: products.id,
        code: products.code,
        name: products.name,
        unit: products.unit,
        volume: products.volume,
        retailPrice: products.retailPrice,
        unitPrice: products.unitPrice,
        discountPercent: products.discountPercent,
        note: products.note,
        groupName: productGroups.name,
      })
      .from(products)
      .leftJoin(productGroups, eq(products.groupId, productGroups.id))
      .where(
        and(
          eq(products.tenantId, session.tenantId),
          eq(products.isActive, true),
          params.nhom ? eq(products.groupId, params.nhom) : undefined,
          params.q ? or(ilike(products.name, `%${params.q}%`), ilike(products.code, `%${params.q}%`)) : undefined,
        ),
      )
      .orderBy(asc(products.code))
      .limit(500),
  ]);

  return (
    <>
      <PageHeader
        title="Sản phẩm"
        subtitle="Bảng giá dùng để báo giá, lên đơn, báo cáo và cảnh báo. Giá bán lẻ và giá đại lý đều đã gồm VAT."
        actions={
          <Link href="/don-hang" className="btn-ghost">
            ← Đơn hàng
          </Link>
        }
      />

      <form className="mb-4 flex flex-wrap items-end gap-3" action="/san-pham">
        <div className="min-w-48 flex-1">
          <label htmlFor="q" className="label-caps mb-1.5 block">
            Tìm kiếm
          </label>
          <input id="q" name="q" defaultValue={params.q ?? ""} className="input" placeholder="Mã hoặc tên sản phẩm…" />
        </div>
        <div>
          <label htmlFor="nhom" className="label-caps mb-1.5 block">
            Nhóm
          </label>
          <select id="nhom" name="nhom" defaultValue={params.nhom ?? ""} className="input">
            <option value="">Tất cả</option>
            {groups.map((g) => (
              <option key={g.id} value={g.id}>
                {g.name}
              </option>
            ))}
          </select>
        </div>
        <button type="submit" className="btn-ghost">
          Lọc
        </button>
      </form>

      {rows.length === 0 ? (
        <EmptyState message="Không tìm thấy sản phẩm." />
      ) : (
        <>
          <div className="flex flex-col gap-2 md:hidden">
            {rows.map((p) => (
              <div key={p.id} className="card p-3.5">
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="font-semibold text-ink-700">{p.name}</div>
                    <div className="text-[11px] text-ink-400">
                      {p.code} · {p.groupName ?? "—"} · {p.unit}
                      {p.volume ? ` · ${p.volume}` : ""}
                    </div>
                  </div>
                  <div className="shrink-0 text-right">
                    <div className="tnum text-sm font-bold text-ink-700">{formatVnd(Number(p.unitPrice))}</div>
                    <div className="text-[10px] uppercase tracking-wide text-ink-400">giá đại lý</div>
                  </div>
                </div>
                <div className="mt-1.5 flex flex-wrap gap-x-3 text-xs text-ink-500">
                  {Number(p.retailPrice) > 0 && <span>Lẻ {formatVnd(Number(p.retailPrice))}</span>}
                  {Number(p.discountPercent) > 0 && <span>CK {p.discountPercent}%</span>}
                </div>
                {p.note && <div className="mt-1 text-xs text-ink-400">{p.note}</div>}
              </div>
            ))}
          </div>

          <div className="hidden md:block">
            <TableWrap>
              <thead>
                <tr>
                  <th>Mã SP</th>
                  <th>Tên sản phẩm</th>
                  <th>Nhóm</th>
                  <th>ĐVT</th>
                  <th>Dung tích / TL</th>
                  <th className="text-right">Giá bán lẻ (có VAT)</th>
                  <th className="text-right">Giá đại lý (có VAT)</th>
                  <th className="text-right">Chiết khấu (%)</th>
                  <th>Ghi chú</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((p) => (
                  <tr key={p.id}>
                    <td className="tnum text-ink-400">{p.code}</td>
                    <td className="font-medium text-ink-700">{p.name}</td>
                    <td className="text-ink-500">{p.groupName ?? "—"}</td>
                    <td className="text-ink-500">{p.unit}</td>
                    <td className="text-ink-500">{p.volume ?? "—"}</td>
                    <td className="tnum text-right text-ink-500">
                      {Number(p.retailPrice) > 0 ? formatVnd(Number(p.retailPrice)) : "—"}
                    </td>
                    <td className="tnum text-right font-medium">{formatVnd(Number(p.unitPrice))}</td>
                    <td className="tnum text-right text-ink-500">
                      {Number(p.discountPercent) > 0 ? `${p.discountPercent}%` : "—"}
                    </td>
                    <td className="max-w-xs text-xs text-ink-500">{p.note ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
        </>
      )}
    </>
  );
}
