import { fetchJoDetail } from "@/app/api/jo";
import { SearchParams, ServerFetchError } from "@/app/utils/fetchUtil";
import JoSave from "@/components/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";

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

type Props = SearchParams;

const JoEdit: 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("Job Order not found:", e);
    } else {
      console.error("Error fetching Job Order detail:", e);
    }
    notFound();
  }

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

export default JoEdit;