import { getDictionary } from "@/i18n";
import { sanityFetch } from "@/sanity/client";
import { EVENTS_QUERY } from "@/sanity/queries";
import { PageHeader, Container, SectionHeading, JoinCta } from "@/components/ui";
import { Reveal } from "@/components/reveal";
import { EventCard, FeaturedEventCard } from "@/components/cards";

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

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const d = getDictionary(locale);
  return { title: d.events.title, description: d.events.lead };
}

export default async function EventsPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const dict = getDictionary(locale);
  const events = await sanityFetch<any[]>(EVENTS_QUERY, {}, []);
  const now = Date.now();
  const upcoming = events.filter(
    (e) => e.startDateTime && new Date(e.startDateTime).getTime() >= now,
  );
  const past = events
    .filter((e) => !(e.startDateTime && new Date(e.startDateTime).getTime() >= now))
    .reverse();

  const featured = upcoming[0];
  const upcomingRest = upcoming.slice(1);

  return (
    <>
      <PageHeader eyebrow={dict.nav.events} title={dict.events.title} lead={dict.events.lead} />

      <Container>
        <div className="space-y-16 py-16 sm:py-20">
          {events.length === 0 && (
            <p className="text-center text-muted">{dict.empty.events}</p>
          )}

          {featured && (
            <Reveal>
              <FeaturedEventCard event={featured} locale={locale} dict={dict} />
            </Reveal>
          )}

          {upcomingRest.length > 0 && (
            <div>
              <SectionHeading title={dict.events.upcoming} />
              <div className="mt-8 grid gap-5 sm:grid-cols-2">
                {upcomingRest.map((e, i) => (
                  <Reveal key={e._id} delay={(i % 2) * 0.06}>
                    <EventCard event={e} locale={locale} dict={dict} />
                  </Reveal>
                ))}
              </div>
            </div>
          )}

          {past.length > 0 && (
            <div>
              <SectionHeading title={dict.events.past} />
              <div className="mt-8 grid gap-5 sm:grid-cols-2">
                {past.map((e, i) => (
                  <Reveal key={e._id} delay={(i % 2) * 0.06}>
                    <EventCard event={e} locale={locale} dict={dict} />
                  </Reveal>
                ))}
              </div>
            </div>
          )}
        </div>
      </Container>

      <JoinCta locale={locale} dict={dict} />
    </>
  );
}
