import { fetchJoDetail } from "@/app/api/jo";
import { SearchParams, ServerFetchError } from "@/app/utils/fetchUtil";
import JoSave from "@/components/JoSave/JoSave";
import PageTitleBar from "@/components/PageTitleBar";
import { I18nProvider, getServerI18n } from "@/i18n";
import { isArray } from "lodash";
import { Metadata } from "next";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import GeneralLoading from "@/components/General/GeneralLoading";

export const metadata: Metadata = {
  title: "Edit Job Order Detail",
};

type Props = SearchParams;

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

  if (!id || isArray(id) || !isFinite(parseInt(id))) {
    notFound();
  }

  try {
    await fetchJoDetail(parseInt(id));
  } catch (e) {
    if (
      e instanceof ServerFetchError &&
      (e.response?.status === 404 || e.response?.status === 400)
    ) {
      console.log(e);
      notFound();
    }
  }

  return (
    <>
      <PageTitleBar title={t("Edit Job Order Detail")} className="mb-4" />
      <I18nProvider namespaces={["jo","navigation","common"]}>
        <Suspense fallback={<GeneralLoading />}>
          <JoSave id={parseInt(id)} defaultValues={undefined} />
        </Suspense>
      </I18nProvider>
    </>
  );
};

export default JodetailEdit;