import { Metadata } from "next";
import { getServerI18n, I18nProvider } from "@/i18n";
import Typography from "@mui/material/Typography";
import { fetchQcItemDetails, preloadQcItem } from "@/app/api/settings/qcItem";
import QcItemSave from "@/components/QcItemSave";
import { isArray } from "lodash";
import { notFound } from "next/navigation";
import { ServerFetchError } from "@/app/utils/fetchUtil";

export const metadata: Metadata = {
  title: "Qc Item",
};

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

const qcItem: React.FC<Props> = async ({ searchParams }) => {
  const { t } = await getServerI18n("qcItem");

  const id = searchParams["id"];

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

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

  return (
    <>
      <Typography variant="h4" marginInlineEnd={2}>
        {t("Edit Qc Item")}
      </Typography>
      <I18nProvider namespaces={["qcItem"]}>
        <QcItemSave id={id} />
      </I18nProvider>
    </>
  );
};

export default qcItem;
