import { getClient } from "@/app/client";
import { Blocks } from "@/components/blocks/Blocks";
import { Breadcrumb } from "@/components/general/Breadcrumb";
import { ImageFigure } from "@/components/general/Image";
import { graphql } from "@/gql";
import { NewsFragment } from "@/gql/graphql";
import { formatDate, formatExtendedDateTime } from "@/lib/date";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  const allNewsSlugsQuery = graphql(`
    query allNewsSlugs {
      pages(contentType: "news.NewsPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allNewsSlugsQuery, {});

  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 newsBySlugQuery = graphql(`
    query newsBySlug($slug: String!) {
      news: page(contentType: "news.NewsPage", slug: $slug) {
        ... on NewsPage {
          ...News
        }
      }
    }
  `);

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

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

  const news = (data?.news ?? {}) as NewsFragment;
  const featuredImage: any = news.featuredImage;

  return (
    <main className="site-main" id="main">
      <section className="news-header">
        <Breadcrumb link="/aktuelt" text="Nyhet" date={formatDate(news.firstPublishedAt, "d. MMMM yyyy")} />
        <h1 className="news-title">{news.title}</h1>
        {news.lead && (
          <div
            className="lead"
            dangerouslySetInnerHTML={{ __html: news.lead }}
          />
        )}
        {featuredImage && (
          <ImageFigure
            src={featuredImage.url}
            alt={featuredImage.alt ?? ""}
            width={featuredImage.width}
            height={featuredImage.height}
            attribution={featuredImage.attribution}
            sizes="100vw"
          />
        )}
      </section>
      <section className="pageContent">
        <Blocks blocks={news.body} />
      </section>
    </main>
  );
}
