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 { Metadata } from "next";
import { Suspense } from "react";

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const name = "Cochise Oncology";
  let title = "Page";
  let description = "Page";
  let imgUrl = "";

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

  // check for blog data
  if (!!blog) {
    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;
  }

  // check for page data when blog is not found
  if (!blog) {
    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;
    }
  }

  return {
    title: title,
    description: description,
    openGraph: {
      title: title,
      description: description,
      images: !!imgUrl ? { url: imgUrl } : undefined,
    },
  };
}

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 */}
    </>
  );
}
