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

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

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

    const block = await helpers.poll.get.fetch({ id });

    if(!block) {
        return {
            title: t("dashboard.poll.notFound.title"),
            description: t("dashboard.poll.notFound.description")
        };
    }

    return {
        title: `${t("dashboard.poll.editor.update.title")}: ${block.title || "Untitled Poll"}`,
        description: `${t("dashboard.poll.editor.update.description")} ${block.title || "this poll"}`
    };
}

export default async function Page({ params }: Props) {
    const { id } = await params;
    const helpers = await createHelpers();
    const t = await getTranslations();
    const poll = await helpers.poll.get.fetch({
        with: ["questions"],
        id
    });

    if(!poll) {
        notFound();
    }

    return (
        <DashboardLayout
          title={t("dashboard.poll.editor.update.title")}
          description={t("dashboard.poll.editor.update.description")}
          back={Routes.DASHBOARD.POLL_LIST}>
            <DashboardBreadcrump>
                <DashboardBreadcrump.Item href={Routes.DASHBOARD.POLL_LIST}>
                    {t("dashboard.poll.list.title")}
                </DashboardBreadcrump.Item>
                <DashboardBreadcrump.Item active>
                    {t("dashboard.poll.editor.update.title")}
                </DashboardBreadcrump.Item>
            </DashboardBreadcrump>

            <PollEditor mode="edit" data={poll} />
            <PollStats poll={poll} />
        </DashboardLayout>
    );
}
