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

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

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

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

  const abilities = await fetchUserAbilities();

  if (![MAINTAIN_PROJECT].some((ability) => abilities.includes(ability))) {
    notFound();
  }

  const draftId = isString(searchParams["draftId"])
    ? parseInt(searchParams["draftId"])
    : undefined;

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

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

export default Projects;
