import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Clock, MapPin, ArrowRight } from "lucide-react";
import { getDictionary, pick } from "@/i18n";
import { sanityFetch, slugStaticParams } from "@/sanity/client";
import { EVENT_QUERY, EVENT_SLUGS_QUERY, EVENTS_QUERY } from "@/sanity/queries";
import { Container, SectionHeading } from "@/components/ui";
import { Reveal } from "@/components/reveal";
import { SanityImage } from "@/components/sanity-image";
import { RichText } from "@/components/portable-text";
import { EventCard } from "@/components/cards";
import { formatDate, formatTimeRange } from "@/lib/format";

/* eslint-disable @typescript-eslint/no-explicit-any */

export async function generateStaticParams() {
  return slugStaticParams(EVENT_SLUGS_QUERY);
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const e = await sanityFetch<any>(EVENT_QUERY, { slug }, null);
  if (!e) return {};
  return { title: pick(e.title, locale), description: pick(e.summary, locale) };
}

export default async function EventPage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const dict = getDictionary(locale);
  const [e, allEvents] = await Promise.all([
    sanityFetch<any>(EVENT_QUERY, { slug }, null),
    sanityFetch<any[]>(EVENTS_QUERY, {}, []),
  ]);
  if (!e) notFound();

  const others = (allEvents || []).filter((x) => x.slug?.current !== slug).slice(0, 2);

  return (
    <article>
      {/* Cover hero */}
      <div className="relative h-[44vh] min-h-72 w-full overflow-hidden bg-brand-deep">
        {e.image ? (
          <SanityImage
            image={e.image}
            alt={pick(e.title, locale) || ""}
            priority
            sizes="100vw"
            className="h-full w-full object-cover"
          />
        ) : (
          <div aria-hidden className="radiance animate-gradient absolute inset-0 opacity-80" />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-ink/80 via-ink/30 to-transparent" />
        <div className="absolute inset-x-0 bottom-0">
          <Container>
            <div className="pb-10">
              <Link
                href={`/${locale}/events/`}
                className="inline-flex items-center gap-1.5 text-sm font-semibold text-white/90 transition hover:gap-2.5"
              >
                <ArrowLeft className="size-4" />
                {dict.nav.events}
              </Link>
              <h1 className="mt-4 max-w-3xl text-balance text-4xl leading-tight tracking-tight text-white sm:text-5xl">
                {pick(e.title, locale)}
              </h1>
            </div>
          </Container>
        </div>
      </div>

      <Container narrow>
        <div className="py-12">
          {/* When / where */}
          <div className="flex flex-wrap gap-x-10 gap-y-5 rounded-2xl border border-line bg-surface p-6 shadow-card">
            <div>
              <p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-brand-bright">
                <Clock className="size-3.5" /> {dict.events.when}
              </p>
              <p className="mt-2 text-ink-soft">
                {formatDate(e.startDateTime, locale, {
                  weekday: "long",
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })}
              </p>
              <p className="text-ink-soft">
                {formatTimeRange(e.startDateTime, e.endDateTime, locale)}
              </p>
            </div>
            {e.location && (
              <div>
                <p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-brand-bright">
                  <MapPin className="size-3.5" /> {dict.events.where}
                </p>
                <p className="mt-2 text-ink-soft">{e.location}</p>
              </div>
            )}
          </div>

          {e.registrationUrl && (
            <a
              href={e.registrationUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-6 inline-flex items-center gap-2 rounded-sm bg-brand px-7 py-3.5 text-sm font-semibold text-bg transition hover:bg-brand-deep"
            >
              {dict.events.register}
              <ArrowRight className="size-4" />
            </a>
          )}

          <div className="py-10">
            <RichText value={pick(e.description, locale)} />
          </div>
        </div>
      </Container>

      {others.length > 0 && (
        <section className="border-t border-line bg-surface py-16 sm:py-20">
          <Container>
            <SectionHeading
              title={dict.events.upcoming}
              action={{ href: `/${locale}/events/`, label: dict.cta.viewAll }}
            />
            <div className="mt-8 grid gap-5 sm:grid-cols-2">
              {others.map((x, i) => (
                <Reveal key={x._id} delay={i * 0.06}>
                  <EventCard event={x} locale={locale} dict={dict} />
                </Reveal>
              ))}
            </div>
          </Container>
        </section>
      )}
    </article>
  );
}
