import Link from "next/link";
import { notFound } from 'next/navigation';
import BlockResolver from "@/components/BlockResolver/BlockResolver";
import { getCachedAllPosts, getCachedPost } from "@/services/wp";
import type { Metadata } from "next";
import { unescapeHtml } from "@/utils/unescapeHtml";
import PageTitle from "@/blocks/PageTitle";
import Section from "@/components/Section/Section";
import Container from "@/components/Container/Container";
import { generateMeta } from "@/utils/generateMeta";
import { stripHtmlTags } from "@/utils/stripHtmlTags";
import Badge from "@/components/Badge/Badge";
import { DEFAULT_OG_IMAGE } from "@/utils/constants";
import { Article, WithContext } from "schema-dts";
import BreadcrumbLayout from "@/layouts/BreadcrumbLayout";

const Post = async (props: { params: Promise<{ postSlug: string }> }) => {
  const params = await props.params;
  let posts: Awaited<ReturnType<typeof getCachedPost>> = [];

  try {
    posts = await getCachedPost(params.postSlug);
  } catch {
    notFound();
  }

  const post = posts[0];

  if (!post) {
    notFound();
  }

  const title = unescapeHtml(post.title.rendered);
  const description = stripHtmlTags(unescapeHtml(post.excerpt.rendered || ""));
  const siteUrl = process.env.SITE_URL || "https://teapot.agency";
  const url = `${siteUrl}/insights/${params.postSlug}`;
  const image = post.featured_media?.source_url || DEFAULT_OG_IMAGE;
  const datePublished = post.date;
  const dateModified = post.modified || post.date;
  const authorName = post.author?.name || "Teapot";

  const articleJsonLd: WithContext<Article> = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: title,
    description,
    url,
    mainEntityOfPage: url,
    image: [image],
    datePublished,
    dateModified,
    author: {
      "@type": "Person",
      name: authorName,
    },
    publisher: {
      "@type": "Organization",
      name: "Teapot",
      logo: {
        "@type": "ImageObject",
        url: `${siteUrl}/image/teapot.svg`,
      },
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }}
      />
      <BreadcrumbLayout
        siteUrl={siteUrl}
        items={[
          { label: "Home", href: "/" },
          { label: "Insights", href: "/insights" },
          { label: title, href: `/insights/${params.postSlug}` },
        ]}
      >
        <PageTitle title={title} supporting_title={"INSIGHTS"} />
        <BlockResolver blocks={post.blocks_json} />
        <Container>
          <Section
            className="grid auto-rows-auto grid-cols-1 p-none"
            gridArea="thin"
          >
            <p className="h3 lg:px-none lg:m-none w-full">
              <Link
                href={"/insights"}
                className={"flex flex-row justify-start items-center gap-xs"}
              >
                <Badge
                  className={"mt-[3px] select-none transform rotate-[225deg]"}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    height="24"
                    viewBox="0 -960 960 960"
                    width="24"
                  >
                    <path d="M647-440H160v-80h487L423-744l57-56 320 320-320 320-57-56 224-224Z" />
                  </svg>
                </Badge>
                <span>Back to Insights</span>
              </Link>
            </p>
          </Section>
        </Container>
      </BreadcrumbLayout>
    </>
  );
};

export async function generateStaticParams() {
  try {
    const posts = await getCachedAllPosts(100, ["publish"]);
    const postList = Array.isArray(posts) ? posts : [];

    return postList
      .filter((post: any) => post?.slug)
      .map((post: any) => ({
        postSlug: post.slug,
      }));
  } catch {
    return [];
  }
}


export const generateMetadata = async (
  props: {
    params: Promise<{ postSlug: string }>;
  }
): Promise<Metadata> => {
  const params = await props.params;
  let post: Awaited<ReturnType<typeof getCachedPost>> = [];

  try {
    post = await getCachedPost(params.postSlug);
  } catch {
    return generateMeta([], "insights");
  }

  return generateMeta(post, "insights");
};

export default Post;
