import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import { Breadcrumb } from "@/components/general/Breadcrumb";
import { ImageFigure } from "@/components/general/Image";
import { PageContent } from "@/components/general/PageContent";
import { graphql } from "@/gql";
import { NewsFragment } from "@/gql/graphql";
import { formatDate } from "@/lib/date";
import { getSeoMetadata } from "@/lib/seo";

const newsBySlugQuery = graphql(`
  query newsBySlug($slug: String!) {
    news: page(contentType: "news.NewsPage", slug: $slug) {
      ... on NewsPage {
        ...News
      }
    }
  }
`);

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

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error(
      "Failed to generate static params for subpages of /aktuelt"
    );
  }

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

type Params = Promise<{ slug: string }>;

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { slug } = await params;
  const { data, error } = await getClient().query(newsBySlugQuery, {
    slug,
  });
  if (error) {
    throw new Error(error.message);
  }
  if (!data?.news) {
    return null;
  }
  const news = data.news as NewsFragment;
  const metadata = await getSeoMetadata(news, parent);
  return metadata;
}

export default async function Page({ params }: { params: Params }) {
  const { slug } = await params;
  const { data, error } = await getClient().query(newsBySlugQuery, {
    slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.news) {
    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={news.firstPublishedAt ? 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>
      <PageContent blocks={news.body} />
    </main>
  );
}
