import { fetchTaskTemplateDetail, preloadAllTasks } from "@/app/api/tasks";
import CreateTaskTemplate from "@/components/CreateTaskTemplate";
import { getServerI18n } from "@/i18n";
import Typography from "@mui/material/Typography";
import { Metadata } from "next";
import { I18nProvider } from "@/i18n";
import { ServerFetchError } from "@/app/utils/fetchUtil";
import { isArray } from "lodash";
import { notFound } from "next/navigation";

export const metadata: Metadata = {
  title: "Edit Task Template",
};

interface Props {
  searchParams: { [key: string]: string | string[] | undefined };
}

const TaskTemplates: React.FC<Props> = async ({ searchParams }) => {
  const { t } = await getServerI18n("tasks");
  const taskTemplateId = searchParams["id"];

  if (!taskTemplateId || isArray(taskTemplateId)) {
    notFound();
  }

  preloadAllTasks();

  try {
    await fetchTaskTemplateDetail(taskTemplateId);
  } catch (e) {
    if (e instanceof ServerFetchError && e.response?.status === 404) {
      notFound();
    }
  }

  return (
    <>
      <Typography variant="h4">{t("Edit Task Template")}</Typography>
      <I18nProvider namespaces={["tasks", "common"]}>
        <CreateTaskTemplate taskTemplateId={taskTemplateId}/>
      </I18nProvider>
    </>
  );
};

export default TaskTemplates;
