import { Metadata } from 'next';
import { getTranslations } from "next-intl/server";
import { notFound } from 'next/navigation';
import { createHelpers } from '@/lib/trpc/server';
import { PostPreview } from '@/app/dashboard/posts/[slug]/_components/post-preview';
import { DashboardLayout, DashboardBreadcrump } from "@/components/layout/dashboard";
import { Routes } from "@/config/routes";

type Props = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;

  try {
    const helpers = await createHelpers();
    const post = await helpers.posts.get.fetch({
      access: 'dashboard',
      slug
    });

    if (!post) {
      return {
        title: 'Post Not Found',
        description: 'The requested post could not be found.'
      };
    }

    return {
      title: post.title || 'Untitled Post',
      description: `Preview of ${post.title || 'this post'}`
    };
  } catch {
    return {
      title: 'Post Not Found',
      description: 'The requested post could not be found.'
    };
  }
}

export default async function PostPage({ params }: Props) {
  const { slug } = await params;
  const t = await getTranslations();

  const helpers = await createHelpers();
  const post = await helpers.posts.get.fetch({
    with: [
      'author',
      'project',
      'projectPosts',
      'vision',
      'primaryTag',
      'tags',
      'review',
      'postMedia',
      'content'
    ],
    access: 'dashboard',
    slug
  });

  if (!post) {
    notFound();
  }

  return (
    <DashboardLayout
      title={t("dashboard.post.view.title")}
      back={Routes.DASHBOARD.POST_LIST}
    >
      <DashboardBreadcrump>
        <DashboardBreadcrump.Item href={Routes.DASHBOARD.POST_LIST}>{t("dashboard.post.list.title")}</DashboardBreadcrump.Item>
        <DashboardBreadcrump.Item>{t("dashboard.post.view.title")}</DashboardBreadcrump.Item>
      </DashboardBreadcrump>

      <PostPreview post={post} />
    </DashboardLayout>
  );
}
