import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks";
import CreateProject from "./CreateProject";
import {
  fetchMainProjects,
  fetchProjectBuildingTypes,
  fetchProjectCategories,
  fetchProjectContractTypes,
  fetchProjectDetails,
  fetchProjectFundingTypes,
  fetchProjectLocationTypes,
  fetchProjectServiceTypes,
  fetchProjectWorkNatures,
} from "@/app/api/projects";
import { fetchStaff, fetchTeamLeads } from "@/app/api/staff";
import {
  fetchAllCustomers,
  fetchAllSubsidiaries,
  fetchCustomerTypes,
} from "@/app/api/customer";
import { fetchGrades } from "@/app/api/grades";
import { fetchUserAbilities } from "@/app/utils/fetchUtil";

type CreateProjectProps = {
  isEditMode: false;
  isSubProject?: boolean;
};
interface EditProjectProps {
  isEditMode: true;
  projectId?: string;
  isSubProject?: boolean;
}

type Props = CreateProjectProps | EditProjectProps;

const CreateProjectWrapper: React.FC<Props> = async (props) => {
  const [
    tasks,
    taskTemplates,
    projectCategories,
    teamLeads,
    allCustomers,
    allSubsidiaries,
    contractTypes,
    fundingTypes,
    locationTypes,
    serviceTypes,
    buildingTypes,
    workNatures,
    allStaffs,
    grades,
    customerTypes,
    abilities,
  ] = await Promise.all([
    fetchAllTasks(),
    fetchTaskTemplates(),
    fetchProjectCategories(),
    fetchTeamLeads(),
    fetchAllCustomers(),
    fetchAllSubsidiaries(),
    fetchProjectContractTypes(),
    fetchProjectFundingTypes(),
    fetchProjectLocationTypes(),
    fetchProjectServiceTypes(),
    fetchProjectBuildingTypes(),
    fetchProjectWorkNatures(),
    fetchStaff(),
    fetchGrades(),
    fetchCustomerTypes(),
    fetchUserAbilities(),
  ]);

  const projectInfo = props.isEditMode
    ? await fetchProjectDetails(props.projectId!)
    : undefined;

  const mainProjects = Boolean(props.isSubProject)
    ? await fetchMainProjects()
    : undefined;

  return (
    <CreateProject
      isEditMode={props.isEditMode}
      isSubProject={Boolean(props.isSubProject)}
      defaultInputs={projectInfo}
      allTasks={tasks}
      projectCategories={projectCategories}
      taskTemplates={taskTemplates}
      teamLeads={teamLeads}
      allSubsidiaries={allSubsidiaries}
      allCustomers={allCustomers}
      contractTypes={contractTypes}
      fundingTypes={fundingTypes}
      locationTypes={locationTypes}
      serviceTypes={serviceTypes}
      buildingTypes={buildingTypes}
      workNatures={workNatures}
      allStaffs={allStaffs}
      grades={grades}
      customerTypes={customerTypes}
      mainProjects={mainProjects}
      abilities={abilities}
    />
  );
};

export default CreateProjectWrapper;
