import { getClient } from "@/app/client";
import { Blocks } from "@/components/blocks/Blocks";
import { Breadcrumb } from "@/components/general/Breadcrumb";
import Icon from "@/components/general/Icon";
import { Image } from "@/components/general/Image";
import { graphql } from "@/gql";
import { AssociationFragment } from "@/gql/graphql";
import Link from "next/link";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  const allAssociationSlugsQuery = graphql(`
    query allAssociationSlugs {
      pages(contentType: "associations.AssociationPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allAssociationSlugsQuery, {});

  if (data === undefined || error) {
    throw new Error("failed to generate static params");
  }

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

export default async function Page({ params }: { params: { slug: string } }) {
  const associationBySlugQuery = graphql(`
    query associationBySlug($slug: String!) {
      association: page(
        contentType: "associations.AssociationPage"
        slug: $slug
      ) {
        ... on AssociationPage {
          ...Association
        }
      }
    }
  `);

  const { data, error } = await getClient().query(associationBySlugQuery, {
    slug: params.slug,
  });

  if (data?.association === null || error) {
    return notFound();
  }

  const association = (data?.association ?? {}) as AssociationFragment;

  return (
    <main className="site-main" id="main">
      <Breadcrumb link="/foreninger" text={association.associationType ? association.associationType : "Foreninger"} />
      <section className="page-header">
        <h1>{association.title}</h1>
        {association.websiteUrl && (
          <a className="button" href={association.websiteUrl} target="_blank">
            <span>Besøk nettside</span>
            <Icon type="externalLink" />
          </a>
        )}
        {association.logo && (
          <Image
            src={association.logo.url}
            alt={`Logoen til ${association.title}`}
            width={association.logo.width}
            height={association.logo.height}
            sizes="100vw"
          />
        )}
      </section>
      <section className="pageContent">
        <Blocks blocks={association.body} />
      </section>
    </main>
  );
}
