import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { format } from "date-fns";
import { ArrowLeft, Receipt } from "lucide-react";
import { getCurrentRole } from "@/lib/auth";
import { formatPrice } from "@/lib/format";
import { getAdminOrderDetail } from "@db/queries/admin-orders";
import { Card, PageHeader, StatusPill, TableShell, type Tone } from "@/components/ui";
import { METHOD_LABELS, STATUS_TONE } from "../labels";
import OrderAdminActions from "./order-admin-actions";
import { UpgradePanel } from "@/app/dashboard/events/[id]/buyers-table";

export const metadata = { title: "Order · Admin" };

const TICKET_TONE: Record<string, Tone> = { valid: "ok", used: "info", void: "danger" };

export default async function AdminOrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const { id } = await params;
  const detail = await getAdminOrderDetail(id);
  if (!detail) notFound();
  const { order: o, tickets } = detail;

  const fields: [string, React.ReactNode][] = [
    ["Buyer", o.buyerName || "—"],
    ["Email", o.buyerEmail],
    ["Phone", o.buyerPhone || "—"],
    [
      "Event",
      <>
        {o.eventTitle ?? "—"}
        {o.eventStartsAt && <span className="text-be-muted"> · {format(o.eventStartsAt, "PP")}</span>}
      </>,
    ],
    [
      "Organizer",
      o.organizerId ? (
        <Link href={`/admin/orders?organizer=${o.organizerId}`} className="hover:underline">
          {o.organizerName || "Unnamed"}
          {o.organizerEmail && <span className="text-be-muted"> · {o.organizerEmail}</span>}
        </Link>
      ) : (
        "—"
      ),
    ],
    ["Ordered", format(o.createdAt, "PPpp")],
    ["Amount", formatPrice(o.totalCents, o.currency) + (o.discountCents ? ` (after ${formatPrice(o.discountCents, o.currency)} off${o.couponCode ? `, ${o.couponCode}` : ""})` : "")],
    ["Payment method", METHOD_LABELS[o.paymentMethod] ?? o.paymentMethod],
    ["M-Pesa receipt", o.mpesaReceipt ? <span className="font-mono">{o.mpesaReceipt}</span> : "—"],
    ...(o.mpesaCheckoutRequestId
      ? ([["M-Pesa request", <span key="c" className="font-mono text-xs">{o.mpesaCheckoutRequestId}</span>]] as [string, React.ReactNode][])
      : []),
    ["Order ID", <span key="i" className="font-mono text-xs">{o.id}</span>],
  ];

  return (
    <div className="space-y-6">
      <Link href="/admin/orders" className="inline-flex items-center gap-1 text-sm text-be-muted hover:text-be-text">
        <ArrowLeft className="h-4 w-4" /> All orders
      </Link>

      <PageHeader
        icon={Receipt}
        title={o.buyerName || o.buyerEmail}
        description={`${o.eventTitle ?? "Unknown event"} · ${formatPrice(o.totalCents, o.currency)}`}
        actions={<StatusPill tone={STATUS_TONE[o.status]}>{o.status}</StatusPill>}
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_22rem]">
        <Card>
          <dl className="grid grid-cols-[9rem_1fr] gap-x-4 gap-y-2 text-sm">
            {fields.map(([k, v]) => (
              <div key={k} className="contents">
                <dt className="text-be-muted">{k}</dt>
                <dd className="min-w-0 break-words text-be-text">{v}</dd>
              </div>
            ))}
          </dl>
        </Card>

        <OrderAdminActions
          orderId={o.id}
          status={o.status}
          paymentMethod={o.paymentMethod}
          canQueryMpesa={o.paymentMethod === "mpesa" && Boolean(o.mpesaCheckoutRequestId)}
          hasPendingItems={Array.isArray(o.pendingItems) && o.pendingItems.length > 0}
          ticketCount={tickets.length}
          buyerEmail={o.buyerEmail}
          buyerPhone={o.buyerPhone}
          buyerName={o.buyerName}
          eventTitle={o.eventTitle ?? "your event"}
        />
      </div>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Tickets ({tickets.length})</h2>
        {tickets.length === 0 ? (
          <p className="text-sm text-be-muted">
            {o.status === "paid" ? "Paid, but no tickets were issued." : "No tickets yet. They're issued once the payment is confirmed."}
          </p>
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Ticket type</th>
                <th>Attendee</th>
                <th>Code</th>
                <th>Status</th>
                <th>Checked in</th>
              </tr>
            </thead>
            <tbody>
              {tickets.map((t) => (
                <tr key={t.id}>
                  <td className="text-be-text">{t.ticketTypeName ?? "—"}</td>
                  <td className="text-be-muted">{t.attendeeName || "—"}</td>
                  <td className="font-mono text-xs text-be-muted">{t.code.slice(0, 8)}…</td>
                  <td>
                    <StatusPill tone={TICKET_TONE[t.status] ?? "muted"}>{t.status}</StatusPill>
                  </td>
                  <td className="whitespace-nowrap text-be-muted">
                    {t.checkedInAt ? `${format(t.checkedInAt, "PP p")}${t.checkedInGate ? ` · ${t.checkedInGate}` : ""}` : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
        {o.status === "paid" && tickets.some((t) => t.status === "valid") && (
          <Card>
            <UpgradePanel
              canEdit
              order={{
                id: o.id,
                name: o.buyerName,
                email: o.buyerEmail,
                phone: o.buyerPhone,
                createdAt: o.createdAt.toISOString(),
                method: o.paymentMethod,
                total: formatPrice(o.totalCents, o.currency),
                status: "paid",
                tickets: tickets.map((t) => ({
                  id: t.id,
                  code: t.code,
                  typeName: t.ticketTypeName ?? "Ticket",
                  status: t.status,
                  admitsCount: t.admitsCount ?? 1,
                })),
              }}
            />
          </Card>
        )}
      </section>
    </div>
  );
}
