import routeFactory from '@/assets/constants/routeFactory';
import images from '@/assets/images/images';
import Breadcrumb from '@/components/layout/breadcrumb';
import { IBreadcrumbItem } from '@/components/layout/breadcrumb/breadcrumb';
import ContentGenerator from '@/components/layout/contentGenerator';
import InnerPageBanner from '@/components/layout/innerPages/banner';
import { IPageParams } from '@/models/layout';
import { getPost } from '@/services/blog';
import { getTranslations } from 'next-intl/server';
import { notFound } from 'next/navigation';

interface IParams {
  id: string;
}

export async function generateMetadata({
  params,
}: {
  params: IPageParams<IParams>;
}) {
  const paramsData = await params;
  const { id: postId, locale } = paramsData;
  const t = await getTranslations({ locale });
  const postData = await getPost(postId).catch(() => null);

  if (!postData) {
    return {
      title: t('page_blog'),
      description: t('page_blog_metadata_description'),
    };
  }

  return {
    title: postData.title,
    description: t('page_blog_metadata_description'),
  };
}

export default async function PostPage({
  params,
}: {
  params: IPageParams<IParams>;
}) {
  const paramsData = await params;
  const t = await getTranslations({ locale: paramsData.locale });
  const { id: postId, locale } = paramsData;
  const routes = routeFactory(t, locale);

  const postData = await getPost(postId).catch((error) => {
    if (error?.response?.status === 404) {
      notFound();
    }
    throw error;
  });

  const breadcrumbItems = [
    {
      ...routes.blog,
      href: routes.blog.route(),
    },
    { title: postData?.title },
  ] as IBreadcrumbItem[];

  return (
    <main className="flex flex-col items-center justify-between">
      <InnerPageBanner
        subtitle={postData.title}
        imageSrc={images.blogBanner.src}
      />
      <div className="container-fluid mx-auto my-12 md:my-24">
        <Breadcrumb items={breadcrumbItems} />
        {postData.content && postData.content.length ? (
          <ContentGenerator data={postData.content} className="mt-10" />
        ) : (
          <></>
        )}
      </div>
    </main>
  );
}
