import Link from "next/link";
import { redirect } from "next/navigation";
import { Store } from "lucide-react";
import { getCurrentRole } from "@/lib/auth";
import { listShopsForAdmin } from "@db/queries/merch";
import { EmptyState, PageHeader, StatusPill, TableShell } from "@/components/ui";
import AdminShopToggle from "./shop-toggle";
import AdminDbError, { dbErrorMessage } from "@/components/admin-db-error";

export const metadata = { title: "Merch shops · Admin" };
export const dynamic = "force-dynamic";

// Why is (or isn't) each organizer's merch on the public /shop page?
export default async function AdminMerchShopsPage() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const { shops, loadError } = await listShopsForAdmin()
    .then((shops) => ({ shops, loadError: null as string | null }))
    .catch((err) => {
      console.error("[admin/merch-shops] query failed:", err);
      return { shops: [] as Awaited<ReturnType<typeof listShopsForAdmin>>, loadError: dbErrorMessage(err) };
    });
  const visible = shops.filter((s) => s.visible).length;

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Store}
        title="Merch shops"
        description="Every organizer's shop and whether buyers can see it. A shop shows on vibepasstickets.com/shop only when it's open AND has at least one active product."
      />

      {loadError && <AdminDbError what="merch shops" error={loadError} />}

      <p className="text-sm text-be-muted">
        {shops.length === 0
          ? "No organizer has set up a shop yet."
          : `${visible} of ${shops.length} shop${shops.length === 1 ? " is" : "s are"} visible to buyers.`}
      </p>

      {shops.length === 0 ? (
        <EmptyState
          icon={Store}
          title="No shops yet"
          body="An organizer creates their shop under Dashboard → Merch, then adds products. Nothing appears on the site until they do."
        />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Shop</th>
              <th>Owner</th>
              <th className="text-right">Products</th>
              <th>On the site?</th>
              <th className="text-right" />
            </tr>
          </thead>
          <tbody>
            {shops.map((s) => (
              <tr key={s.id}>
                <td>
                  <span className="font-medium text-be-text">{s.name}</span>
                  <span className="block font-mono text-xs text-be-muted">/shop/{s.slug}</span>
                </td>
                <td className="text-be-muted">
                  {s.ownerName || "Unnamed"}
                  {s.ownerEmail && <span className="block text-xs">{s.ownerEmail}</span>}
                </td>
                <td className="text-right tabular-nums text-be-text">
                  {s.activeCount} active / {s.productCount}
                  <span className="block text-xs text-be-muted">{s.inStockCount} in stock</span>
                </td>
                <td>
                  {s.visible ? (
                    <>
                      <StatusPill tone="ok">Visible</StatusPill>
                      <Link href={`/shop/${s.slug}`} className="ml-2 text-xs text-brand-green-h hover:underline" target="_blank">
                        View
                      </Link>
                      {s.inStockCount === 0 && (
                        <span className="block text-xs text-be-muted">Everything is sold out</span>
                      )}
                    </>
                  ) : (
                    <>
                      <StatusPill tone="warn">Hidden</StatusPill>
                      <span className="block text-xs text-be-muted">{s.reason}</span>
                    </>
                  )}
                </td>
                <td className="text-right">
                  <AdminShopToggle shopId={s.id} open={s.open} />
                </td>
              </tr>
            ))}
          </tbody>
        </TableShell>
      )}
    </div>
  );
}
