import Link from "next/link";
import { redirect } from "next/navigation";
import { format } from "date-fns";
import { CalendarDays, MapPin, Plus, ChevronRight } from "lucide-react";
import { eq, asc } from "drizzle-orm";
import { db } from "@db/client";
import { events } from "@db/schema";
import { getDashboardUser } from "@/lib/view-as";
import type { EventStatus } from "@/lib/types";
import { PageHeader, LinkButton, EmptyState, StatusPill, type Tone } from "@/components/ui";

const STATUS_TONE: Record<EventStatus, Tone> = {
  draft: "muted",
  published: "ok",
  cancelled: "danger",
};

export default async function DashboardEventsPage({
  searchParams,
}: {
  searchParams: Promise<{ notice?: string }>;
}) {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const { notice } = await searchParams;

  // Scope to the signed-in organizer's own events -- there's no RLS
  // backstop anymore, so this filter is now the only thing standing
  // between an organizer and every other organizer's events.
  const myEvents = await db
    .select()
    .from(events)
    .where(eq(events.organizerId, user.id))
    .orderBy(asc(events.startsAt));

  return (
    <div className="space-y-6">
      {notice === "admin-required" && (
        <div className="pill-warn rounded-lg p-4 text-sm">
          <p className="font-medium">That link is for platform staff only</p>
          <p className="mt-1 text-xs opacity-80">
            Your account doesn&apos;t have admin access, so you&apos;ve been brought here to your own dashboard instead.
          </p>
        </div>
      )}

      <PageHeader
        icon={CalendarDays}
        title="Your events"
        description="Karibu! Let's get your event live."
        actions={
          <LinkButton href="/dashboard/events/new" icon={Plus}>
            Create event
          </LinkButton>
        }
      />

      {!myEvents.length ? (
        <EmptyState
          icon={CalendarDays}
          title="No events yet"
          body="Create your first event to start selling tickets."
          action={
            <LinkButton href="/dashboard/events/new" icon={Plus}>
              Create event
            </LinkButton>
          }
        />
      ) : (
        <div className="grid gap-3">
          {myEvents.map((ev) => (
            <Link
              key={ev.id}
              href={`/dashboard/events/${ev.id}`}
              className="be-card be-card-hover group flex items-center justify-between gap-4 p-4"
            >
              <div className="min-w-0">
                <h2 className="truncate font-medium text-be-text">{ev.title}</h2>
                <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-be-muted">
                  <span className="inline-flex items-center gap-1.5">
                    <CalendarDays className="h-3.5 w-3.5" />
                    {format(ev.startsAt, "PPp")}
                  </span>
                  <span className="inline-flex items-center gap-1.5">
                    <MapPin className="h-3.5 w-3.5" />
                    {ev.venue || "No venue set"}
                  </span>
                </p>
              </div>
              <div className="flex shrink-0 items-center gap-3">
                <StatusPill tone={STATUS_TONE[ev.status as EventStatus] ?? "muted"}>
                  {ev.status}
                </StatusPill>
                <ChevronRight className="h-4 w-4 text-be-muted transition-transform group-hover:translate-x-0.5" />
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
