import { graphql } from "@/gql";
import { NewsFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { Breadcrumb } from "@/components/general/Breadcrumb";
import { ImageFigure } from "@/components/general/Image";
import { PageContent } from "@/components/general/PageContent";
import { RichText } from "@/components/general/RichText";
import { formatDate } from "@/lib/date";

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

export type NewsPageViewProps = { news: NewsFragment };

export async function loadNewsPageProps(args: {
  slug?: string;
  newsOverride?: NewsFragment;
}): Promise<NewsPageViewProps | null> {
  if (args.newsOverride) {
    return { news: args.newsOverride };
  }
  if (!args.slug) throw new Error("loadNewsPageProps needs slug or newsOverride");
  const { data, error } = await getClient().query(newsBySlugQuery, {
    slug: args.slug,
  });
  if (error) throw new Error(error.message);
  const news = data?.news as NewsFragment | undefined;
  if (!news) return null;
  return { news };
}

export function NewsPageView({ news }: NewsPageViewProps) {
  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">
            <RichText content={news.lead} />
          </div>
        )}
        {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>
  );
}
