import { redirect } from "next/navigation";
import { and, eq, inArray } from "drizzle-orm";
import { db } from "@db/client";
import { events, orders, users } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { format } from "date-fns";
import { CalendarX2 } from "lucide-react";
import {
  getPendingCancellationRequests,
  getResolvedCancellationRequests,
  type CancellationStatus,
} from "@db/queries/cancellations";
import CancellationResolveActions from "./cancellation-resolve-actions";
import { PageHeader, TableShell, StatusPill, EmptyState, type Tone } from "@/components/ui";

export const metadata = { title: "Cancellations · Admin" };

const STATUS_TONE: Record<CancellationStatus, Tone> = {
  pending: "warn",
  approved: "danger",
  rejected: "muted",
  withdrawn: "muted",
};

export default async function AdminCancellationsPage() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const [pending, resolved] = await Promise.all([
    getPendingCancellationRequests(),
    getResolvedCancellationRequests(25),
  ]);

  const all = [...pending, ...resolved];
  const eventIds = [...new Set(all.map((r) => r.event_id))];
  const orgIds = [...new Set(all.map((r) => r.organizer_id))];
  const pendingEventIds = [...new Set(pending.map((r) => r.event_id))];

  const [eventRows, userRows, paidRows] = await Promise.all([
    eventIds.length
      ? db
          .select({ id: events.id, title: events.title, startsAt: events.startsAt })
          .from(events)
          .where(inArray(events.id, eventIds))
      : [],
    orgIds.length
      ? db.select({ id: users.id, name: users.name, email: users.email }).from(users).where(inArray(users.id, orgIds))
      : [],
    // Paid orders on events awaiting a decision -- what approving would put in the refunds queue.
    pendingEventIds.length
      ? db
          .select({ eventId: orders.eventId })
          .from(orders)
          .where(and(inArray(orders.eventId, pendingEventIds), eq(orders.status, "paid")))
      : [],
  ]);

  const eventById = new Map(eventRows.map((e) => [e.id, e]));
  const orgById = new Map(userRows.map((u) => [u.id, u.name || u.email || "Unnamed"]));
  const paidOrdersByEvent = new Map<string, number>();
  for (const o of paidRows) paidOrdersByEvent.set(o.eventId, (paidOrdersByEvent.get(o.eventId) ?? 0) + 1);

  return (
    <div className="space-y-8">
      <PageHeader
        icon={CalendarX2}
        title="Cancellations"
        description="Organizers request; you decide. Approving cancels the event, voids every ticket so it won't scan, and queues a refund request per paid order in Refunds for you to issue. Rejecting leaves the event untouched."
      />

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Pending requests</h2>
        {pending.length === 0 ? (
          <EmptyState
            icon={CalendarX2}
            title="No pending cancellation requests"
            body="When an organizer asks to cancel an event, it lands here."
          />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Requested</th>
                <th>Event</th>
                <th>Reason</th>
                <th className="text-right">Paid orders</th>
                <th className="text-right">Action</th>
              </tr>
            </thead>
            <tbody>
              {pending.map((r) => {
                const event = eventById.get(r.event_id);
                const paidCount = paidOrdersByEvent.get(r.event_id) ?? 0;
                return (
                  <tr key={r.id}>
                    <td className="whitespace-nowrap text-be-muted">{format(new Date(r.created_at), "PP")}</td>
                    <td>
                      <span className="font-medium text-be-text">{event?.title ?? "—"}</span>
                      <span className="block text-xs text-be-muted">
                        {orgById.get(r.organizer_id) ?? "Unnamed"}
                        {event?.startsAt ? ` · ${format(event.startsAt, "PP")}` : ""}
                      </span>
                    </td>
                    <td className="max-w-xs text-be-muted">{r.reason}</td>
                    <td className="text-right tabular-nums text-be-text">{paidCount}</td>
                    <td className="text-right">
                      <CancellationResolveActions
                        requestId={r.id}
                        eventTitle={event?.title ?? "this event"}
                        paidOrders={paidCount}
                      />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </TableShell>
        )}
      </section>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Recently resolved</h2>
        {resolved.length === 0 ? (
          <EmptyState icon={CalendarX2} title="Nothing resolved yet" body="Resolved requests will appear here." />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Resolved</th>
                <th>Event</th>
                <th>Reason</th>
                <th>Outcome</th>
              </tr>
            </thead>
            <tbody>
              {resolved.map((r) => (
                <tr key={r.id}>
                  <td className="whitespace-nowrap text-be-muted">
                    {r.resolved_at ? format(new Date(r.resolved_at), "PP") : "—"}
                  </td>
                  <td>
                    <span className="font-medium text-be-text">{eventById.get(r.event_id)?.title ?? "—"}</span>
                    <span className="block text-xs text-be-muted">{orgById.get(r.organizer_id) ?? "Unnamed"}</span>
                  </td>
                  <td className="max-w-xs text-be-muted">{r.reason}</td>
                  <td>
                    <StatusPill tone={STATUS_TONE[r.status]}>{r.status}</StatusPill>
                    {r.resolution_note && (
                      <span className="mt-1 block text-xs text-be-muted">{r.resolution_note}</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
      </section>
    </div>
  );
}
