import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { format } from "date-fns";
import { ArrowLeft, Coins, MousePointerClick, ShoppingBag, Ticket, TrendingUp } from "lucide-react";
import { getDashboardUser } from "@/lib/view-as";
import { getAffiliateSales, getMyAffiliate } from "@db/queries/affiliates";
import { formatPrice } from "@/lib/format";
import { Card, EmptyState, PageHeader, StatCard, StatusPill, TableShell } from "@/components/ui";

export const metadata = { title: "Affiliate · Dashboard" };

// One promoter's sales: every paid order that came through their link, who
// bought, for which event, and how many tickets of each type (Regular, VIP,
// VVIP...). Organizer-scoped: getMyAffiliate/getAffiliateSales only return
// the signed-in organizer's own data.
export default async function AffiliateDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const { id } = await params;
  const affiliate = await getMyAffiliate(user.id, id);
  if (!affiliate) notFound();
  const sales = await getAffiliateSales(user.id, id);

  const tickets = sales.reduce((s, o) => s + o.ticketCount, 0);
  const salesCents = sales.reduce((s, o) => s + o.totalCents, 0);
  const commissionCents = sales.reduce((s, o) => s + o.commissionCents, 0);

  // Tickets per type, per event: "VULAI FESTIVAL: 5 Regular, 2 VIP".
  const byEvent = new Map<string, { title: string; orders: number; byType: Map<string, number> }>();
  for (const s of sales) {
    const e = byEvent.get(s.eventId) ?? { title: s.eventTitle, orders: 0, byType: new Map<string, number>() };
    e.orders += 1;
    for (const t of s.ticketsByType) e.byType.set(t.name, (e.byType.get(t.name) ?? 0) + t.count);
    byEvent.set(s.eventId, e);
  }

  return (
    <div className="space-y-8">
      <Link href="/dashboard/affiliates" className="inline-flex items-center gap-1 text-sm text-be-muted hover:text-be-text">
        <ArrowLeft className="h-4 w-4" /> All affiliates
      </Link>

      <PageHeader
        title={affiliate.name || affiliate.code}
        description={`Code ${affiliate.code} · ${affiliate.commission_percent}% commission`}
        actions={
          affiliate.active ? <StatusPill tone="ok">Active</StatusPill> : <StatusPill tone="muted">Disabled</StatusPill>
        }
      />

      <section className="grid grid-cols-2 gap-3 sm:grid-cols-5">
        <StatCard icon={MousePointerClick} label="Link clicks" value={affiliate.total_clicks.toString()} />
        <StatCard icon={ShoppingBag} label="Orders" value={sales.length.toString()} />
        <StatCard icon={Ticket} label="Tickets sold" value={tickets.toString()} />
        <StatCard icon={TrendingUp} label="Sales" value={formatPrice(salesCents, "kes")} />
        <StatCard icon={Coins} label="Commission earned" value={formatPrice(commissionCents, "kes")} accent="gold" />
      </section>

      {sales.length === 0 ? (
        <EmptyState
          icon={Ticket}
          title="No sales through this link yet"
          body="When someone buys after opening this promoter's link, the order shows up here."
        />
      ) : (
        <>
          <section className="space-y-3">
            <h2 className="text-lg font-medium text-be-text">Tickets by type</h2>
            <div className="grid gap-3 sm:grid-cols-2">
              {[...byEvent].map(([eventId, e]) => (
                <Card key={eventId}>
                  <p className="font-medium text-be-text">{e.title}</p>
                  <p className="mb-3 text-xs text-be-muted">
                    {e.orders} order{e.orders === 1 ? "" : "s"}
                  </p>
                  <dl className="space-y-1.5 text-sm">
                    {[...e.byType]
                      .sort(([, a], [, b]) => b - a)
                      .map(([name, n]) => (
                        <div key={name} className="flex items-center justify-between">
                          <dt className="text-be-muted">{name}</dt>
                          <dd className="font-medium tabular-nums text-be-text">{n}</dd>
                        </div>
                      ))}
                  </dl>
                </Card>
              ))}
            </div>
          </section>

          <section className="space-y-3">
            <h2 className="text-lg font-medium text-be-text">Buyers through this link</h2>
            <TableShell>
              <thead>
                <tr>
                  <th>When</th>
                  <th>Buyer</th>
                  <th>Event</th>
                  <th>Tickets</th>
                  <th className="text-right">Amount</th>
                  <th className="text-right">Commission</th>
                </tr>
              </thead>
              <tbody>
                {sales.map((s) => (
                  <tr key={s.orderId}>
                    <td className="whitespace-nowrap text-be-muted">{format(s.createdAt, "PP p")}</td>
                    <td>
                      <span className="text-be-text">{s.buyerName || s.buyerEmail}</span>
                      <span className="block text-xs text-be-muted">
                        {s.buyerEmail}
                        {s.buyerPhone && <> · {s.buyerPhone}</>}
                      </span>
                    </td>
                    <td className="text-be-text">{s.eventTitle}</td>
                    <td className="text-be-text">
                      {s.ticketsByType.map((t) => `${t.count} × ${t.name}`).join(", ") || "—"}
                    </td>
                    <td className="text-right tabular-nums text-be-text">{formatPrice(s.totalCents, "kes")}</td>
                    <td className="text-right tabular-nums text-be-text">{formatPrice(s.commissionCents, "kes")}</td>
                  </tr>
                ))}
              </tbody>
            </TableShell>
          </section>
        </>
      )}
    </div>
  );
}
