import Link from "next/link";
import { redirect } from "next/navigation";
import { desc, inArray } from "drizzle-orm";
import { db } from "@db/client";
import { events, users } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { format } from "date-fns";
import { CalendarDays, Star } from "lucide-react";
import type { EventApprovalStatus, EventStatus } from "@/lib/types";
import EventAdminActions from "./event-admin-actions";
import { PageHeader, TableShell, StatusPill, EmptyState, type Tone } from "@/components/ui";

export const metadata = { title: "Events · Admin" };

const STATUS_TONE: Record<EventStatus, Tone> = {
  draft: "muted",
  published: "ok",
  cancelled: "danger",
};

const APPROVAL_TONE: Record<EventApprovalStatus, Tone> = {
  unsubmitted: "muted",
  pending: "warn",
  approved: "ok",
  rejected: "danger",
};
const APPROVAL_LABEL: Record<EventApprovalStatus, string> = {
  unsubmitted: "not submitted",
  pending: "awaiting approval",
  approved: "approved",
  rejected: "rejected",
};

export default async function AdminEventsPage() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const rows = await db
    .select({
      id: events.id,
      title: events.title,
      status: events.status,
      approvalStatus: events.approvalStatus,
      approvalNote: events.approvalNote,
      featured: events.featured,
      startsAt: events.startsAt,
      organizerId: events.organizerId,
      organizerName: events.organizerName,
    })
    .from(events)
    .orderBy(desc(events.startsAt));

  // Events waiting for review go to the top.
  const rank = (s: EventApprovalStatus) => (s === "pending" ? 0 : 1);
  rows.sort((a, b) => rank(a.approvalStatus) - rank(b.approvalStatus));
  const pendingCount = rows.filter((e) => e.approvalStatus === "pending").length;

  const ids = [...new Set(rows.map((e) => e.organizerId))];
  const profiles = ids.length ? await db.select({ id: users.id, name: users.name }).from(users).where(inArray(users.id, ids)) : [];
  const nameById = new Map(profiles.map((p) => [p.id, p.name]));

  return (
    <div className="space-y-6">
      <PageHeader
        icon={CalendarDays}
        title="Events"
        description="Every organizer's events. Approve new ones, feature them on the homepage or take them down."
      />

      {pendingCount > 0 && (
        <div className="rounded-lg p-4 text-sm pill-warn">
          <span className="font-semibold">
            {pendingCount} event{pendingCount === 1 ? "" : "s"} waiting for approval
          </span>{" "}
          — shown first below. Approving publishes the event; rejecting sends the organizer your reason.
        </div>
      )}

      {rows.length === 0 ? (
        <EmptyState icon={CalendarDays} title="No events yet" body="Events appear here as organizers create them." />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Event</th>
              <th>Organizer</th>
              <th>When</th>
              <th>Status</th>
              <th className="text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((e) => (
              <tr key={e.id}>
                <td>
                  <Link href={`/admin/orders?event=${e.id}`} className="font-medium text-be-text hover:underline" title="View orders">
                    {e.title}
                  </Link>
                  {e.featured && (
                    <span className="ml-2 inline-flex items-center gap-1 text-xs text-brand-gold-h">
                      <Star className="h-3 w-3 fill-current" /> featured
                    </span>
                  )}
                </td>
                <td className="text-be-muted">
                  {nameById.get(e.organizerId) || e.organizerName || (
                    <span className="opacity-60">Unnamed</span>
                  )}
                </td>
                <td className="whitespace-nowrap text-be-muted">
                  {format(e.startsAt, "PP")}
                </td>
                <td>
                  <StatusPill tone={STATUS_TONE[e.status] ?? "muted"}>
                    {e.status}
                  </StatusPill>
                  {e.approvalStatus !== "approved" && (
                    <span className="ml-1.5">
                      <StatusPill tone={APPROVAL_TONE[e.approvalStatus]}>{APPROVAL_LABEL[e.approvalStatus]}</StatusPill>
                    </span>
                  )}
                  {e.approvalStatus === "rejected" && e.approvalNote && (
                    <p className="mt-1 max-w-xs text-xs text-be-muted">“{e.approvalNote}”</p>
                  )}
                </td>
                <td className="text-right">
                  <EventAdminActions
                    eventId={e.id}
                    featured={e.featured}
                    status={e.status}
                    approvalStatus={e.approvalStatus}
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </TableShell>
      )}
    </div>
  );
}
