import { fetchAllCustomers, fetchAllSubsidiaries } from "@/app/api/customer";
import { fetchGrades } from "@/app/api/grades";
import {
  fetchProjectBuildingTypes,
  fetchProjectCategories,
  fetchProjectContractTypes,
  fetchProjectDetails,
  fetchProjectFundingTypes,
  fetchProjectLocationTypes,
  fetchProjectServiceTypes,
  fetchProjectWorkNatures,
} from "@/app/api/projects";
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff";
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks";
import { ServerFetchError } from "@/app/utils/fetchUtil";
import CreateProject from "@/components/CreateProject";
import { I18nProvider, getServerI18n } from "@/i18n";
import Typography from "@mui/material/Typography";
import { isArray } from "lodash";
import { Metadata } from "next";
import { notFound } from "next/navigation";

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

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

const Projects: React.FC<Props> = async ({ searchParams }) => {
  const { t } = await getServerI18n("projects");
  // Assume projectId is string here
  const projectId = searchParams["id"];

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

  // Preload necessary dependencies
  fetchAllTasks();
  fetchTaskTemplates();
  fetchProjectCategories();
  fetchProjectContractTypes();
  fetchProjectFundingTypes();
  fetchProjectLocationTypes();
  fetchProjectServiceTypes();
  fetchProjectBuildingTypes();
  fetchProjectWorkNatures();
  fetchAllCustomers();
  fetchAllSubsidiaries();
  fetchGrades();
  preloadTeamLeads();
  preloadStaff();

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

  return (
    <>
      <Typography variant="h4">{t("Edit Project")}</Typography>
      <I18nProvider namespaces={["projects"]}>
        <CreateProject isEditMode projectId={projectId} />
      </I18nProvider>
    </>
  );
};

export default Projects;
