import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import { EventDetails } from "@/components/events/EventDetails";
import { EventHeader } from "@/components/events/EventHeader";
import { BgPig } from "@/components/general/BgPig";
import { PageContent } from "@/components/general/PageContent";
import { graphql } from "@/gql";
import { EventFragment } from "@/gql/graphql";
import { getEventPig } from "@/lib/event";
import { getSeoMetadata } from "@/lib/seo";

const eventBySlugQuery = graphql(`
  query eventBySlug($slug: String!) {
    event: page(contentType: "events.EventPage", slug: $slug) {
      ... on EventPage {
        ...Event
      }
    }
  }
`);

export async function generateStaticParams() {
  const allEventSlugsQuery = graphql(`
    query allEventSlugs {
      pages(contentType: "events.EventPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allEventSlugsQuery, {});

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error(
      "Failed to generate static params for subpages of /arrangementer"
    );
  }

  return data.pages.map((page: any) => ({
    slug: page.slug,
  }));
}

type Params = Promise<{ slug: string }>;

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { slug } = await params;
  const { data, error } = await getClient().query(eventBySlugQuery, {
    slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.event) {
    return null;
  }

  const event = data.event as EventFragment;
  const metadata = await getSeoMetadata(event, parent);
  return metadata;
}

export default async function Page({ params }: { params: Params }) {
  const { slug } = await params;
  const { data, error } = await getClient().query(eventBySlugQuery, {
    slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.event) {
    return notFound();
  }

  const event = data.event as EventFragment;
  const eventPig = getEventPig(event);

  return (
    <>
      <main className="site-main" id="main">
        <EventHeader event={event} />
        <EventDetails event={event} />
        {event.lead && (
          <div
            className="lead event-lead"
            dangerouslySetInnerHTML={{ __html: event.lead }}
          />
        )}
        <PageContent blocks={event.body} />
      </main>
      {eventPig && <BgPig type={eventPig} color="white" />}
    </>
  );
}
