import Link from "next/link";
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { format } from "date-fns";
import { Receipt, Search } from "lucide-react";
import { db } from "@db/client";
import { users } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { formatPrice } from "@/lib/format";
import { searchAdminOrders, type OrderStatus } from "@db/queries/admin-orders";
import { PageHeader, TableShell, StatusPill, EmptyState, buttonClass } from "@/components/ui";
import { METHOD_LABELS, STATUS_TONE } from "./labels";

export const metadata = { title: "Orders · Admin" };

const STATUSES: OrderStatus[] = ["paid", "pending", "cancelled", "refunded"];

export default async function AdminOrdersPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string; organizer?: string; event?: string }>;
}) {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const sp = await searchParams;
  const q = sp.q?.trim() || undefined;
  const status = STATUSES.includes(sp.status as OrderStatus) ? (sp.status as OrderStatus) : undefined;
  const organizerId = sp.organizer || undefined;
  const eventId = sp.event || undefined;

  const [rows, organizer] = await Promise.all([
    searchAdminOrders({ q, status, organizerId, eventId, limit: 100 }),
    organizerId
      ? db.select({ name: users.name }).from(users).where(eq(users.id, organizerId)).limit(1).then((r) => r[0])
      : undefined,
  ]);

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Receipt}
        title="Orders & buyers"
        description="Every organizer's orders, tickets and buyers. Open an order to check an M-Pesa payment, issue tickets that didn't arrive, or resend them by email and SMS."
      />

      <form className="flex flex-wrap items-end gap-2" action="/admin/orders">
        <label className="min-w-[16rem] flex-1">
          <span className="mb-1 block text-xs text-be-muted">Buyer name, email, phone, M-Pesa receipt, order ID or event</span>
          <input name="q" defaultValue={q} placeholder="e.g. 0712 345 678 or SIT4ABC12D" className="be-input w-full" />
        </label>
        <label>
          <span className="mb-1 block text-xs text-be-muted">Status</span>
          <select name="status" defaultValue={status ?? ""} className="be-input">
            <option value="">Any</option>
            {STATUSES.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>
        </label>
        {organizerId && <input type="hidden" name="organizer" value={organizerId} />}
        {eventId && <input type="hidden" name="event" value={eventId} />}
        <button type="submit" className={buttonClass("primary")}>
          <Search className="h-4 w-4" /> Search
        </button>
      </form>

      {(organizerId || eventId) && (
        <p className="text-sm text-be-muted">
          {organizerId && <>Showing orders for <strong className="text-be-text">{organizer?.name || "this organizer"}</strong>. </>}
          {eventId && <>Filtered to one event. </>}
          <Link href="/admin/orders" className="text-brand-green-h hover:underline">
            Show all organizers
          </Link>
        </p>
      )}

      {rows.length === 0 ? (
        <EmptyState
          icon={Receipt}
          title={q || status ? "No matching orders" : "No orders yet"}
          body={q ? "Try the buyer's phone number, email or M-Pesa receipt." : "Orders appear here as buyers check out."}
        />
      ) : (
        <>
          <TableShell>
            <thead>
              <tr>
                <th>Date</th>
                <th>Buyer</th>
                <th>Event</th>
                <th>Payment</th>
                <th className="text-right">Amount</th>
                <th className="text-right">Tickets</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((o) => (
                <tr key={o.id}>
                  <td className="whitespace-nowrap text-be-muted">
                    <Link href={`/admin/orders/${o.id}`} className="hover:underline">
                      {format(o.createdAt, "PP p")}
                    </Link>
                  </td>
                  <td>
                    <Link href={`/admin/orders/${o.id}`} className="font-medium text-be-text hover:underline">
                      {o.buyerName || o.buyerEmail}
                    </Link>
                    <span className="block text-xs text-be-muted">
                      {o.buyerEmail}
                      {o.buyerPhone && <> · {o.buyerPhone}</>}
                    </span>
                  </td>
                  <td>
                    <span className="text-be-text">{o.eventTitle ?? "—"}</span>
                    <span className="block text-xs text-be-muted">{o.organizerName || "Unnamed organizer"}</span>
                  </td>
                  <td className="text-be-text">
                    {METHOD_LABELS[o.paymentMethod] ?? o.paymentMethod}
                    {o.mpesaReceipt && <span className="block font-mono text-xs text-be-muted">{o.mpesaReceipt}</span>}
                  </td>
                  <td className="text-right tabular-nums text-be-text">{formatPrice(o.totalCents, o.currency)}</td>
                  <td className="text-right tabular-nums text-be-text">{o.ticketCount}</td>
                  <td>
                    <StatusPill tone={STATUS_TONE[o.status]}>{o.status}</StatusPill>
                  </td>
                </tr>
              ))}
            </tbody>
          </TableShell>
          {rows.length === 100 && (
            <p className="text-xs text-be-muted">Showing the 100 most recent matches. Search to narrow it down.</p>
          )}
        </>
      )}
    </div>
  );
}
