import Link from "next/link";
import { db } from "@/lib/db";
import { getPublicConference, regState } from "@/lib/conference";
import { dateRange, fmtDate, formatMoney, parseJSON } from "@/lib/utils";
import { Avatar, Badge, Card } from "@/components/ui";
import { SPONSOR_TIER_LABELS, SPEAKER_TYPE_LABELS } from "@/lib/constants";

export default async function ConferenceHome({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const conf = await getPublicConference(slug);
  const [speakers, ticketTypes, counts, announcements] = await Promise.all([
    db.speaker.findMany({ where: { conferenceId: conf.id }, orderBy: [{ featured: "desc" }, { name: "asc" }], take: 8 }),
    db.ticketType.findMany({ where: { conferenceId: conf.id, active: true }, orderBy: { price: "asc" } }),
    db.$transaction([
      db.session.count({ where: { conferenceId: conf.id } }),
      db.speaker.count({ where: { conferenceId: conf.id } }),
      db.registration.count({ where: { conferenceId: conf.id, status: "CONFIRMED" } }),
    ]),
    db.announcement.findMany({ where: { conferenceId: conf.id }, orderBy: [{ pinned: "desc" }, { createdAt: "desc" }], take: 3 }),
  ]);
  const [sessionCount, speakerCount, regCount] = counts;
  const reg = regState(conf);
  const social = parseJSON<Record<string, string>>(conf.socialLinks, {});

  return (
    <main>
      {/* Hero */}
      <section
        className="border-b border-zinc-900"
        style={{ background: `radial-gradient(ellipse at 30% 0%, ${conf.primaryColor}2e, transparent 55%), radial-gradient(ellipse at 90% 20%, ${conf.primaryColor}1a, transparent 50%)` }}
      >
        <div className="mx-auto max-w-6xl px-4 py-20">
          <div className="fx-in flex flex-wrap items-center gap-2 text-xs font-medium uppercase tracking-widest text-zinc-400">
            <Badge className="bg-zinc-800 text-zinc-300">{conf.type}</Badge>
            {conf.category && <Badge className="bg-zinc-800 text-zinc-300">{conf.category}</Badge>}
            {conf.theme && <span className="text-zinc-500">{conf.theme}</span>}
          </div>
          <h1 className="fx-in fx-d1 mt-4 max-w-3xl text-4xl font-bold tracking-tight text-zinc-50 sm:text-5xl">{conf.name}</h1>
          {conf.tagline && <p className="fx-in fx-d2 mt-3 max-w-2xl text-lg text-zinc-400">{conf.tagline}</p>}
          <div className="fx-in fx-d2 mt-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-zinc-300">
            <span className="flex items-center gap-2">📅 {dateRange(conf.startAt, conf.endAt)}</span>
            {conf.venueName && <span className="flex items-center gap-2">📍 {conf.venueName}{conf.city ? `, ${conf.city}` : ""}</span>}
            {conf.type !== "PHYSICAL" && <span className="flex items-center gap-2">🖥️ Online access included</span>}
            <span className="flex items-center gap-2">🌐 {conf.languages ?? "English"}</span>
          </div>
          <div className="fx-in fx-d3 mt-8 flex flex-wrap gap-3">
            {reg === "open" ? (
              <Link
                href={`/c/${conf.slug}/register`}
                className="fx-shine rounded-lg px-5 py-2.5 text-sm font-semibold text-white shadow-lg transition hover:opacity-90"
                style={{ background: conf.primaryColor }}
              >
                Register now {ticketTypes[0] && ticketTypes[0].price === 0 ? "— free passes available" : ""}
              </Link>
            ) : (
              <span className="rounded-lg bg-zinc-800 px-5 py-2.5 text-sm font-medium text-zinc-400">
                {reg === "not_open" ? `Registration opens ${conf.regOpensAt ? fmtDate(conf.regOpensAt) : "soon"}` : "Registration closed"}
              </span>
            )}
            <Link href={`/c/${conf.slug}/schedule`} className="rounded-lg border border-zinc-700 px-5 py-2.5 text-sm font-medium text-zinc-200 transition hover:bg-zinc-800">
              View schedule
            </Link>
          </div>
          <div className="fx-in fx-d4 mt-10 flex gap-8 text-sm">
            {[[sessionCount, "Sessions"], [speakerCount, "Speakers"], [regCount, "Registered"]].map(([n, l]) => (
              <div key={l as string}>
                <div className="text-2xl font-bold text-zinc-100">{n}</div>
                <div className="text-xs uppercase tracking-wider text-zinc-500">{l}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {announcements.length > 0 && (
        <section className="mx-auto max-w-6xl px-4 pt-10">
          <div className="space-y-2">
            {announcements.map((a) => (
              <div key={a.id} className="rounded-lg border border-zinc-800 bg-zinc-900/60 px-4 py-3">
                <span className="mr-2 text-xs font-semibold uppercase tracking-wider" style={{ color: conf.primaryColor }}>
                  {a.pinned ? "📌 " : ""}Announcement
                </span>
                <span className="text-sm font-medium text-zinc-200">{a.title}</span>
                <span className="ml-2 text-sm text-zinc-500">{a.body}</span>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* About */}
      <section className="mx-auto grid max-w-6xl gap-10 px-4 py-14 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <h2 className="text-lg font-semibold text-zinc-100">About the conference</h2>
          <p className="mt-3 whitespace-pre-line text-[15px] leading-relaxed text-zinc-400">{conf.description}</p>
          {conf.tracks.length > 0 && (
            <>
              <h3 className="mt-8 text-sm font-semibold uppercase tracking-wider text-zinc-500">Tracks</h3>
              <div className="mt-3 flex flex-wrap gap-2">
                {conf.tracks.map((t) => (
                  <span key={t.id} className="rounded-full border px-3 py-1 text-sm" style={{ borderColor: `${t.color}55`, color: t.color, background: `${t.color}14` }}>
                    {t.name}
                  </span>
                ))}
              </div>
            </>
          )}
        </div>
        <div className="space-y-4">
          <Card className="p-4">
            <h3 className="text-sm font-semibold text-zinc-200">Venue</h3>
            {conf.type === "VIRTUAL" ? (
              <p className="mt-2 text-sm text-zinc-500">Fully virtual — join links are shared with registered participants.</p>
            ) : (
              <div className="mt-2 text-sm text-zinc-400">
                <div className="font-medium text-zinc-300">{conf.venueName}</div>
                <div className="mt-1 text-zinc-500">{conf.venueAddress}</div>
                <div className="text-zinc-500">{conf.city}{conf.country ? `, ${conf.country}` : ""}</div>
              </div>
            )}
            {conf.type === "HYBRID" && <p className="mt-2 text-xs text-zinc-500">Hybrid event — attend in person or online.</p>}
          </Card>
          <Card className="p-4">
            <h3 className="text-sm font-semibold text-zinc-200">Organized by</h3>
            <div className="mt-2 text-sm font-medium text-zinc-300">{conf.org.name}</div>
            {conf.org.description && <p className="mt-1 text-sm text-zinc-500">{conf.org.description}</p>}
            {Object.keys(social).length > 0 && (
              <div className="mt-3 flex gap-3 text-xs">
                {Object.entries(social).map(([k, v]) => (
                  <a key={k} href={v} target="_blank" rel="noreferrer" className="capitalize text-zinc-500 underline-offset-2 hover:text-zinc-300 hover:underline">{k}</a>
                ))}
              </div>
            )}
          </Card>
          {ticketTypes.length > 0 && (
            <Card className="p-4">
              <h3 className="text-sm font-semibold text-zinc-200">Passes</h3>
              <ul className="mt-2 space-y-2">
                {ticketTypes.map((t) => (
                  <li key={t.id} className="flex items-center justify-between text-sm">
                    <span className="text-zinc-400">{t.name}</span>
                    <span className="font-semibold text-zinc-200">{formatMoney(t.price, t.currency)}</span>
                  </li>
                ))}
              </ul>
              {reg === "open" && (
                <Link href={`/c/${conf.slug}/register`} className="mt-3 block rounded-lg py-2 text-center text-sm font-medium text-white" style={{ background: conf.primaryColor }}>
                  Get your pass
                </Link>
              )}
            </Card>
          )}
        </div>
      </section>

      {/* Speakers preview */}
      {speakers.length > 0 && (
        <section className="border-t border-zinc-900 bg-zinc-900/30">
          <div className="mx-auto max-w-6xl px-4 py-14">
            <div className="flex items-baseline justify-between">
              <h2 className="text-lg font-semibold text-zinc-100">Featured speakers</h2>
              <Link href={`/c/${conf.slug}/speakers`} className="text-sm font-medium hover:underline" style={{ color: conf.primaryColor }}>
                All speakers →
              </Link>
            </div>
            <div className="mt-6 grid grid-cols-2 gap-4 sm:grid-cols-4">
              {speakers.map((s) => (
                <Card key={s.id} className="fx-reveal fx-lift p-4 text-center">
                  <div className="flex justify-center"><Avatar name={s.name} src={s.photoUrl} size={14} /></div>
                  <div className="mt-3 text-sm font-semibold text-zinc-200">{s.name}</div>
                  {s.speakerType !== "SPEAKER" && (
                    <div className="mt-0.5 text-[11px] font-semibold text-violet-600">{SPEAKER_TYPE_LABELS[s.speakerType] ?? s.speakerType}</div>
                  )}
                  <div className="mt-0.5 text-xs text-zinc-500">{s.designation}{s.organization ? `, ${s.organization}` : ""}</div>
                </Card>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Sponsors */}
      {conf.sponsors.length > 0 && (
        <section className="mx-auto max-w-6xl px-4 py-14">
          <h2 className="text-center text-sm font-semibold uppercase tracking-widest text-zinc-500">Sponsors & partners</h2>
          <div className="fx-marquee mt-6">
            <div className="fx-marquee-track">
              {[...conf.sponsors, ...conf.sponsors].map((s, i) => (
                <div
                  key={`${s.id}-${i}`}
                  aria-hidden={i >= conf.sponsors.length}
                  className="flex items-center gap-2.5 whitespace-nowrap rounded-lg border border-zinc-800 bg-zinc-900/60 px-5 py-3 text-sm font-semibold text-zinc-300"
                >
                  {s.logoUrl && (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={s.logoUrl} alt="" className="h-7 w-7 rounded-md bg-white object-contain p-0.5" />
                  )}
                  {s.name}
                  <span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">{SPONSOR_TIER_LABELS[s.tier] ?? s.tier}</span>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}
    </main>
  );
}
