import { Metadata, ResolvingMetadata } from "next";
import { graphql } from "@/gql";
import { AssociationFragment, AssociationIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { AssociationList } from "@/components/associations/AssociationList";
import { PageHeader } from "@/components/general/PageHeader";
import { PageContent } from "@/components/general/PageContent";
import { getSeoMetadata } from "@/lib/seo";

const allAssociationsQuery = graphql(`
  query allAssociations {
    index: associationIndex {
      ... on AssociationIndex {
        ...AssociationIndex
      }
    }
    associations: pages(
      contentType: "associations.AssociationPage"
      limit: 1000
    ) {
      ... on AssociationPage {
        ...Association
      }
    }
  }
`);

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

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

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

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

const AssociationFragmentDefinition = graphql(`
  fragment Association on AssociationPage {
    __typename
    id
    slug
    title
    seoTitle
    searchDescription
    excerpt
    lead
    body {
      ...Blocks
    }
    logo {
      url
      width
      height
    }
    associationType
    websiteUrl
  }
`);

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

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

  const associations = data.associations as AssociationFragment[];
  const index = data.index as AssociationIndexFragment;

  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} />
      {index.body && <PageContent blocks={index.body} />}
      <AssociationList
        associations={associations}
        heading="Foreninger og utvalg"
      />
    </main>
  );
}
