import { Metadata, ResolvingMetadata } from "next";
import { graphql } from "@/gql";
import { VenueFragment, VenueRentalIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { VenueList } from "@/components/venues/VenueList";
import { PageHeader } from "@/components/general/PageHeader";
import { BgPig } from "@/components/general/BgPig";
import { PageContent } from "@/components/general/PageContent";
import { getSeoMetadata } from "@/lib/seo";

const venueRentalIndexQuery = graphql(`
  query venueRentalIndex {
    index: venueRentalIndex {
      ... on VenueRentalIndex {
        ...VenueRentalIndex
      }
    }
    venues: pages(contentType: "venues.VenuePage", limit: 100) {
      ... on VenuePage {
        ...Venue
      }
    }
  }
`);

const VenueRentalIndexDefinition = graphql(`
  fragment VenueRentalIndex on VenueRentalIndex {
    ... on VenueRentalIndex {
      title
      seoTitle
      searchDescription
      lead
      body {
        ...Blocks
      }
    }
  }
`);

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

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

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

export default async function Page() {
  const { data, error } = await getClient().query(venueRentalIndexQuery, {});

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.index || !data?.venues) {
    throw new Error("Failed to render /utleie");
  }

  const index = data.index as VenueRentalIndexFragment;
  const venues = (data?.venues ?? []) as VenueFragment[];
  const bookableVenues = venues.filter((venue) => venue.showAsBookable);

  return (
    <>
      <main className="site-main" id="main">
        <PageHeader heading={index.title} lead={index.lead} />
        {index.body && <PageContent blocks={index.body} />}
        <VenueList venues={bookableVenues} heading="Våre lokaler" />
      </main>
      <BgPig type="key" />
    </>
  );
}
