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

const venueIndexQuery = graphql(`
  query venueIndex {
    index: venueIndex {
      ... on VenueIndex {
        ...VenueIndex
      }
    }
    venues: pages(contentType: "venues.VenuePage", limit: 100) {
      ... on VenuePage {
        ...Venue
      }
    }
  }
`);

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

const VenueFragmentDefinition = graphql(`
  fragment Venue on VenuePage {
    __typename
    id
    slug
    title
    seoTitle
    searchDescription
    images {
      ...Blocks
    }
    body {
      ...Blocks
    }
    featuredImage {
      ...Image
    }
    showAsBookable
    showInOverview
    floor
    preposition
    usedFor
    techSpecsUrl
    capabilityAudio
    capabilityAudioVideo
    capabilityBar
    capabilityLighting
    capacityLegal
    capacityStanding
    capacitySitting
  }
`);

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

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

  const index = (data?.index ?? []) as VenueIndexFragment;
  const metadata = await getSeoMetadata(index, parent);
  return metadata;
}

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

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

  const index = data.index as VenueIndexFragment;
  const venues = (data?.venues ?? []) as VenueFragment[];
  const visibleVenues = venues.filter((x) => x.showInOverview);

  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} />
      <PageContent blocks={index.body} />
      <VenueList venues={visibleVenues} />
    </main>
  );
}
