import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { setRequestLocale } from "next-intl/server";
import { connectDB } from "@/lib/db";
import { Convention } from "@/models/Convention";
import { WaitlistEntry } from "@/models/WaitlistEntry";
import { getSessionClientId } from "@/lib/auth";
import { Link } from "@/i18n/navigation";
import { ScrollReveal } from "@/components/ScrollReveal";
import { WaitlistForm } from "@/components/WaitlistForm";
import { JsonLd } from "@/components/JsonLd";
import { buildPageMetadata, getSiteUrl } from "@/lib/seo";
import { Testimonial } from "@/models/Testimonial";
import { QuickReview } from "@/models/QuickReview";
import { CombinedReviewsBadge } from "@/components/ReviewsWidget";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; id: string }>;
}): Promise<Metadata> {
  const { locale, id } = await params;
  await connectDB();
  const convention = await Convention.findById(id).catch(() => null);
  if (!convention || !convention.visible) {
    return buildPageMetadata({ locale, path: `/conventions/${id}`, title: "Conventions", description: "", noindex: true });
  }

  const isEn = locale === "en";
  const notes = (isEn && convention.notesEn) || convention.notes;
  const description = notes || (isEn ? `Rakku Photography at ${convention.name}.` : `Rakku Photography auf der ${convention.name}.`);
  return buildPageMetadata({ locale, path: `/conventions/${id}`, title: convention.name, description });
}

export default async function ConventionDetailPage({
  params,
}: {
  params: Promise<{ locale: string; id: string }>;
}) {
  const { locale, id } = await params;
  setRequestLocale(locale);
  const isEn = locale === "en";

  await connectDB();
  const convention = await Convention.findById(id).catch(() => null);
  if (!convention || !convention.visible) notFound();

  const [clientId, testimonialDocs, quickReviewDocs] = await Promise.all([
    getSessionClientId(),
    Testimonial.find({ visible: true }).select("rating").lean(),
    QuickReview.find({ visible: true }).select("rating").lean(),
  ]);
  const alreadyOnWaitlist = clientId
    ? Boolean(await WaitlistEntry.findOne({ clientId, conventionId: convention._id }).select("_id").lean())
    : false;

  const notes = (isEn && convention.notesEn) || convention.notes;
  const fmtDate = (d: Date) =>
    new Date(d).toLocaleDateString(isEn ? "en-GB" : "de-DE", { day: "2-digit", month: "long", year: "numeric" });
  const siteUrl = getSiteUrl();

  return (
    <main className="min-h-screen rk-shell pt-32 pb-24">
      <JsonLd
        data={{
          "@context": "https://schema.org",
          "@type": "Event",
          name: convention.name,
          startDate: new Date(convention.startDate).toISOString(),
          endDate: new Date(convention.endDate).toISOString(),
          location: convention.location
            ? { "@type": "Place", name: convention.location }
            : undefined,
          url: `${siteUrl}/${locale}/conventions/${convention._id}`,
          organizer: { "@type": "Person", name: "Rakku Photography" },
        }}
      />

      <ScrollReveal className="max-w-xl mx-auto">
        <Link
          href="/conventions"
          className="text-xs uppercase tracking-[0.15em] text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] transition-colors"
        >
          {isEn ? "← All conventions" : "← Alle Conventions"}
        </Link>

        {convention.logo && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={convention.logo}
            alt=""
            className="mt-6 h-16 w-auto max-w-[14rem] object-contain object-left"
          />
        )}
        <p className="mt-6 text-xs uppercase tracking-[0.35em] text-[var(--rk-ink-muted)]">
          {fmtDate(convention.startDate)}
          {convention.startDate.toString() !== convention.endDate.toString() ? ` – ${fmtDate(convention.endDate)}` : ""}
        </p>
        <h1 className="rk-wordmark mt-3 text-2xl sm:text-3xl">{convention.name}</h1>
        {convention.location && <p className="mt-3 text-sm text-[var(--rk-ink-muted)]">📍 {convention.location}</p>}
        <div className="mt-4">
          <CombinedReviewsBadge
            testimonials={testimonialDocs}
            quickReviews={quickReviewDocs}
            label={isEn ? "Avg. rating" : "Ø Bewertung"}
            countLabel={isEn ? "reviews" : "Bewertungen"}
          />
        </div>
        {notes && <p className="mt-4 text-sm leading-relaxed text-[var(--rk-ink-muted)]">{notes}</p>}
        {convention.infoUrl && (
          <a
            href={convention.infoUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-4 inline-block text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] underline"
          >
            {isEn ? "Convention website ↗" : "Zur Convention-Seite ↗"}
          </a>
        )}

        <div className="mt-8 border-t border-white/10 pt-6">
          <p className="mb-3 text-xs uppercase tracking-[0.14em] text-[var(--rk-accent)]">
            {convention.slotsAvailable
              ? isEn
                ? "Request a slot"
                : "Slot anfragen"
              : isEn
                ? "Fully booked — join the waitlist"
                : "Ausgebucht — auf die Warteliste"}
          </p>
          {alreadyOnWaitlist ? (
            <p className="text-sm text-[var(--rk-ink-muted)]">
              {isEn ? "You're on the list — " : "Du bist eingetragen — "}
              <Link href="/account/conventions" className="underline hover:text-[var(--rk-ink)]">
                {isEn ? "view status" : "Status ansehen"}
              </Link>
            </p>
          ) : clientId ? (
            <WaitlistForm
              conventionId={String(convention._id)}
              locale={locale}
              conventionStart={new Date(convention.startDate).toISOString()}
              conventionEnd={new Date(convention.endDate).toISOString()}
              triggerLabel={
                convention.slotsAvailable
                  ? isEn
                    ? "Request a slot"
                    : "Slot anfragen"
                  : isEn
                    ? "Join waitlist"
                    : "Auf Warteliste eintragen"
              }
            />
          ) : (
            <p className="text-sm text-[var(--rk-ink-muted)]">
              {isEn ? "Please " : "Bitte "}
              <Link href={`/login?next=%2F${locale}%2Fconventions%2F${convention._id}`} className="underline hover:text-[var(--rk-ink)]">
                {isEn ? "log in" : "einloggen"}
              </Link>{" "}
              {isEn ? "or " : "oder "}
              <Link href={`/register?next=%2F${locale}%2Fconventions%2F${convention._id}`} className="underline hover:text-[var(--rk-ink)]">
                {isEn ? "create an account" : "ein Konto erstellen"}
              </Link>{" "}
              {isEn
                ? "to request a slot — you'll then see the status in your account."
                : "um einen Slot anzufragen — den Status siehst du danach in deinem Konto."}
            </p>
          )}
        </div>
      </ScrollReveal>
    </main>
  );
}
