import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { db } from "@/lib/db";
import { stateFromSlug, stateSlug } from "@/lib/constants";
import { Badge, Logo, btn } from "@/components/ui";
import { ConferenceCard } from "@/components/conference-card";
import { IndiaMap } from "@/components/india-map";

export async function generateMetadata({ params }: { params: Promise<{ state: string }> }): Promise<Metadata> {
  const { state } = await params;
  const name = stateFromSlug(state);
  return {
    title: name ? `Conferences in ${name}` : "Conferences",
    description: name ? `Discover upcoming, live and featured conferences happening in ${name} — register in minutes on Confexe.` : undefined,
  };
}

export default async function StateConferencesPage({ params }: { params: Promise<{ state: string }> }) {
  const { state } = await params;
  const stateName = stateFromSlug(state);
  if (!stateName) notFound();

  const [conferences, allStates] = await Promise.all([
    db.conference.findMany({
      where: { state: stateName, status: { in: ["PUBLISHED", "LIVE"] } },
      orderBy: [{ featured: "desc" }, { sponsored: "desc" }, { startAt: "asc" }],
      include: {
        org: true,
        _count: { select: { registrations: { where: { status: "CONFIRMED" } }, sessions: true, speakers: true } },
      },
    }),
    db.conference.groupBy({
      by: ["state"],
      where: { status: { in: ["PUBLISHED", "LIVE"] }, state: { not: null } },
      _count: true,
    }),
  ]);

  const promoted = conferences.filter((c) => c.featured || c.sponsored);
  const rest = conferences.filter((c) => !c.featured && !c.sponsored);
  const liveCount = conferences.filter((c) => c.status === "LIVE").length;
  const mapStats = Object.fromEntries(allStates.filter((s) => s.state).map((s) => [s.state!, { count: s._count, live: 0 }]));
  const otherStates = allStates.filter((s) => s.state && s.state !== stateName);

  const toCard = (c: (typeof conferences)[number]) => ({
    slug: c.slug, name: c.name, tagline: c.tagline, type: c.type, status: c.status,
    category: c.category, city: c.city, state: c.state, startAt: c.startAt, endAt: c.endAt,
    regClosesAt: c.regClosesAt, primaryColor: c.primaryColor, featured: c.featured, sponsored: c.sponsored,
    orgName: c.org.name,
    counts: { sessions: c._count.sessions, speakers: c._count.speakers, registrations: c._count.registrations },
  });

  return (
    <main className="min-h-screen">
      <header className="fx-header sticky top-0 z-30 border-b border-white/60 bg-white/55 backdrop-blur-xl">
        <div className="mx-auto flex h-14 max-w-6xl items-center justify-between px-4">
          <Logo />
          <nav className="flex items-center gap-2">
            <Link href="/#map" className={btn.ghost}>🗺️ India map</Link>
            <Link href="/signup" className={btn.primary}>Get started</Link>
          </nav>
        </div>
      </header>

      {/* State hero */}
      <section className="border-b border-white/60 bg-gradient-to-br from-indigo-500/10 via-transparent to-fuchsia-500/10">
        <div className="mx-auto grid max-w-6xl items-center gap-8 px-4 py-12 lg:grid-cols-[1fr_300px]">
          <div>
            <div className="fx-in flex flex-wrap items-center gap-2">
              <Badge className="bg-indigo-500/10 text-indigo-600">📍 STATE SPOTLIGHT</Badge>
              {liveCount > 0 && <Badge className="bg-emerald-500/10 text-emerald-600">● {liveCount} LIVE NOW</Badge>}
            </div>
            <h1 className="fx-in fx-d1 mt-3 text-4xl font-black text-zinc-100 sm:text-5xl">
              Conferences in{" "}
              <span className="fx-gradient-text bg-gradient-to-r from-indigo-500 via-violet-500 to-fuchsia-500 bg-clip-text text-transparent">{stateName}</span>
            </h1>
            <p className="fx-in fx-d2 mt-3 max-w-xl text-lg text-zinc-500">
              {conferences.length === 0
                ? `No upcoming conferences here yet — organizers, this spot is yours.`
                : `${conferences.length} upcoming ${conferences.length === 1 ? "conference" : "conferences"} — ${promoted.length} promoted. Register in minutes with instant QR tickets.`}
            </p>
            {otherStates.length > 0 && (
              <div className="fx-in fx-d3 mt-5 flex flex-wrap items-center gap-2">
                <span className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Also happening in</span>
                {otherStates.map((s) => (
                  <Link key={s.state} href={`/conferences/in/${stateSlug(s.state!)}`} className="rounded-full border border-white/70 bg-white/60 px-3 py-1 text-xs font-semibold text-indigo-600 backdrop-blur transition hover:bg-white/90">
                    {s.state} · {s._count}
                  </Link>
                ))}
              </div>
            )}
          </div>
          <div className="fx-in fx-d2 hidden lg:block">
            <IndiaMap stats={mapStats} activeState={stateName} />
          </div>
        </div>
      </section>

      <div className="mx-auto max-w-6xl px-4 py-10">
        {promoted.length > 0 && (
          <section>
            <h2 className="flex items-center gap-2 text-lg font-black text-zinc-100">
              ⭐ Featured & sponsored
              <span className="text-sm font-medium text-zinc-500">— hand-picked in {stateName}</span>
            </h2>
            <div className="mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {promoted.map((c) => <ConferenceCard key={c.id} c={toCard(c)} />)}
            </div>
          </section>
        )}

        <section className={promoted.length > 0 ? "mt-12" : ""}>
          <h2 className="text-lg font-black text-zinc-100">
            {promoted.length > 0 ? `All conferences in ${stateName}` : `Conferences in ${stateName}`}
          </h2>
          {rest.length === 0 && promoted.length === 0 ? (
            <div className="mt-6 rounded-2xl border border-dashed border-indigo-200/80 bg-white/40 p-12 text-center backdrop-blur">
              <div className="text-4xl">🗓️</div>
              <p className="mt-3 font-semibold text-zinc-300">Nothing scheduled in {stateName} yet</p>
              <p className="mt-1 text-sm text-zinc-500">Be the first — create a conference here and it appears on the India map instantly.</p>
              <Link href="/signup" className={`${btn.primary} mt-5 inline-flex`}>Host a conference in {stateName}</Link>
            </div>
          ) : rest.length === 0 ? (
            <p className="mt-3 text-sm text-zinc-500">All current conferences in {stateName} are shown above.</p>
          ) : (
            <div className="mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {rest.map((c) => <ConferenceCard key={c.id} c={toCard(c)} />)}
            </div>
          )}
        </section>
      </div>

      <footer className="border-t border-white/60 bg-white/40 py-8 text-center text-xs text-zinc-500 backdrop-blur">
        Confexe · <Link href="/" className="font-semibold text-indigo-600 hover:underline">Explore all of India →</Link>
      </footer>
    </main>
  );
}
