import { Metadata } from "next";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { PostEditor } from "@/components/dashboard/post/post-editor";
import { DashboardLayout, DashboardBreadcrump } from "@/components/layout/dashboard";
import { createHelpers } from "@/lib/trpc/server";
import { Routes } from "@/config/routes";

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

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

    try {
        const helpers = await createHelpers();

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

        if(!post) {
            return {
                title: t("dashboard.post.editor.update.title"),
                description: t("dashboard.post.editor.update.description")
            };
        }

        return {
            title: `${t("dashboard.post.editor.update.title")}: ${post.title || "Untitled Post"}`,
            description: `${t("dashboard.post.editor.update.description")} ${post.title || ""}`
        };
    }
    catch {
        return {
            title: t("dashboard.post.editor.update.title"),
            description: t("dashboard.post.editor.update.description")
        };
    }
}

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

    const helpers = await createHelpers();
    const t = await getTranslations();

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

    if(!post) {
        notFound();
    }

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

            <PostEditor mode="edit" id={post.id} post={post} />
        </DashboardLayout>
    );
}
