import { BlogDetailContentSkeleton } from "@/components/Blogs/BlogDetail";
import HeroOther from "@/components/HeroOther";
import Page from "@/components/Pages/Page";
import { fetchBlogDetail } from "@/services/payload/blog";
import { fetchPageBySlug } from "@/services/payload/page";
import { getDefaultMetadata } from "@/utils/metadata";
import { Metadata } from "next";
import { Suspense } from "react";

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const defaultMetadata = await getDefaultMetadata();
  const name = defaultMetadata.openGraph?.siteName ?? "";
  let title = "Page";
  let description = "Page";
  let publishedAt = "";
  let updatedAt = "";
  let imgUrl = "";

  const slug = (await params).slug;
  const blog = await fetchBlogDetail(slug);

  if (!!blog) {
    // check for blog data
    title = `${!!blog.data?.meta?.title ? blog.data?.meta?.title : blog.data.title} - ${name}`;
    description = `${!!blog.data?.meta?.description ? blog.data?.meta?.description : blog.data.title} - ${name}`;
    imgUrl = blog.imgUrl;
    publishedAt = blog.data.createdAt;
    updatedAt = blog.data.updatedAt;
  } else {
    // check for page data when blog is not found
    const page = await fetchPageBySlug({ slug });
    if (!!page) {
      title = `${!!page?.meta?.title ? page?.meta?.title : page.title} - ${name}`;
      description = `${!!page?.meta?.description ? page?.meta?.description : page.title} - ${name}`;
      imgUrl = page.heroImg?.url;
      publishedAt = page.createdAt;
      updatedAt = page.updatedAt;
    }
  }

  defaultMetadata.title = title;
  defaultMetadata.description = description;
  if (!!defaultMetadata.openGraph) {
    defaultMetadata.openGraph.title = title;
    // @ts-ignore
    defaultMetadata.openGraph.type = "article";
    defaultMetadata.openGraph.description = description;
    defaultMetadata.openGraph.title = title;
    defaultMetadata.openGraph.images = !!imgUrl ? { url: imgUrl } : undefined;
  }
  defaultMetadata.other = {
    "article:published_time": publishedAt,
    "article:modified_time": updatedAt,
  };

  return defaultMetadata;
}

export default async function SinglePage({ params }: { params: Promise<{ slug: string }> }) {
  const slug = (await params).slug;

  return (
    <>
      <Suspense fallback={<Loading />}>
        <Page slug={slug} />
      </Suspense>
    </>
  );
}

function Loading() {
  return (
    <>
      <HeroOther />
      {/* Section */}
      <BlogDetailContentSkeleton />
      {/* End Section */}
    </>
  );
}
