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 { fetchUserAbilities } from "@/app/utils/fetchUtil";
import { ServerFetchError } 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 { 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"];
  const abilities = await fetchUserAbilities()

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

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

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

  return (
    <>
      <I18nProvider namespaces={["projects"]}>
        <CreateProject isEditMode projectId={projectId} />
      </I18nProvider>
    </>
  );
};

export default Projects;
