import { redirect } from "next/navigation";
import { format } from "date-fns";
import { Ticket, Plus } from "lucide-react";
import { getDashboardUser } from "@/lib/view-as";
import { getMyCoupons } from "@db/queries/coupons";
import { formatPrice, nowMs } from "@/lib/format";
import { PageHeader, LinkButton, EmptyState, StatusPill, TableShell } from "@/components/ui";

export const metadata = { title: "Coupons · Dashboard" };

export default async function CouponsPage() {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const coupons = await getMyCoupons(user.id);
  const now = nowMs();

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Ticket}
        title="Coupons"
        description="Early-bird pressure, VIP treats, win-back offers — create a code in seconds."
        actions={
          <LinkButton href="/dashboard/coupons/new" icon={Plus}>
            New coupon
          </LinkButton>
        }
      />

      {coupons.length === 0 ? (
        <EmptyState
          icon={Ticket}
          title="No coupons yet"
          body="Create a discount code to run a promotion on one event or across all of them."
          action={
            <LinkButton href="/dashboard/coupons/new" icon={Plus}>
              New coupon
            </LinkButton>
          }
        />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Code</th>
              <th>Discount</th>
              <th>Scope</th>
              <th className="text-right">Redemptions</th>
              <th>Status</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            {coupons.map((c) => {
              const used = c.redemptions;
              const expired = c.ends_at ? new Date(c.ends_at).getTime() < now : false;
              const exhausted = c.max_redemptions !== null && used >= c.max_redemptions;
              return (
                <tr key={c.id}>
                  <td className="font-mono font-medium text-be-text">{c.code}</td>
                  <td className="text-be-text">
                    {c.kind === "percent" ? `${c.percent_off}% off` : `${formatPrice(c.amount_off_cents ?? 0, "kes")} off`}
                  </td>
                  <td className="text-be-muted">
                    {c.applies_to === "merch" ? "Merch" : c.applies_to === "both" ? "Tickets + merch" : "Tickets"} ·{" "}
                    {c.event_id ? "one event" : "all events"}
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {used}
                    {c.max_redemptions !== null ? ` / ${c.max_redemptions}` : ""}
                  </td>
                  <td>
                    {!c.active ? (
                      <StatusPill tone="muted">Disabled</StatusPill>
                    ) : expired ? (
                      <StatusPill tone="danger">Expired</StatusPill>
                    ) : exhausted ? (
                      <StatusPill tone="warn">Exhausted</StatusPill>
                    ) : (
                      <StatusPill tone="ok">Active</StatusPill>
                    )}
                  </td>
                  <td className="whitespace-nowrap text-be-muted">
                    {format(new Date(c.created_at), "PP")}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </TableShell>
      )}
    </div>
  );
}
