import { Suspense } from "react";
import { Metadata, ResolvingMetadata } from "next";
import { getClient } from "@/app/client";
import { EventContainer } from "@/components/events/EventContainer";
import {
  eventsOverviewQuery,
  eventIndexMetadataQuery,
  EventFragment,
  EventCategory,
  EventOrganizer,
} from "@/lib/event";
import { PageHeader } from "@/components/general/PageHeader";
import { EventIndexFragment, VenueFragment } from "@/gql/graphql";
import { getSeoMetadata } from "@/lib/seo";

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

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

  const index = data.index as EventIndexFragment;
  const metadata = await getSeoMetadata(index, parent);
  return metadata;
}

export default async function Page() {
  const { data, error } = await getClient().query(eventsOverviewQuery, {});
  if (error) {
    throw new Error(error.message);
  }
  if (
    !data?.index ||
    !data?.events?.futureEvents ||
    !data?.eventCategories ||
    !data?.eventOrganizers ||
    !data?.venues
  ) {
    throw new Error("Failed to render /arrangementer");
  }

  const index = data?.index as EventIndexFragment;
  const events = (data?.events?.futureEvents ?? []) as EventFragment[];
  const eventCategories = (data?.eventCategories ?? []) as EventCategory[];
  const eventOrganizers = (data?.eventOrganizers ?? []) as EventOrganizer[];
  const venues = (data?.venues ?? []) as VenueFragment[];

  return (
    <main className="site-main" id="main">
      <PageHeader heading="Dette skjer på Chateau Neuf" align="left" />
      <Suspense>
        <EventContainer
          events={events}
          eventCategories={eventCategories}
          eventOrganizers={eventOrganizers}
          venues={venues}
        />
      </Suspense>
    </main>
  );
}
