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, fetchUserStaff } from "@/app/utils/fetchUtil";
import { MAINTAIN_ALL_PROJECTS } from "@/middleware";

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

interface CopyProjectProps {
  isEditMode?: false;
  isCopyMode: true;
  projectId?: string;
  isSubProject?: boolean;
}

type Props = CreateProjectProps | EditProjectProps | CopyProjectProps;

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 userStaff = await fetchUserStaff();
  const teamId = userStaff?.teamId;

  const isMaintainAllProjectsRight = [MAINTAIN_ALL_PROJECTS].some((ability) =>
    abilities.includes(ability),
  );
  
  var filteredTeamLeads = teamId ? teamLeads.filter(
    (teamLead) => teamLead.teamId === teamId,
  ) : teamLeads
  
  if (userStaff?.id != null && userStaff?.id == 1) {
    filteredTeamLeads = teamLeads.filter(
      (teamLead) => teamLead.teamId === teamId || teamLead.team == "ST",
    )
  }

  if(isMaintainAllProjectsRight){
    filteredTeamLeads = teamLeads
  }
  
  const projectInfo = props.isEditMode || props.isCopyMode
    ? await fetchProjectDetails(props.projectId!)
    : undefined;

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

  if (props.isCopyMode && projectInfo) {
    projectInfo.projectId = null
    projectInfo.projectCode = projectInfo.projectCode + "-copy"
    projectInfo.projectName = projectInfo.projectName + "-copy"
    projectInfo.projectStatus = "" // backend will assign "Pending To Start" status
    Object.entries(projectInfo.milestones).forEach(([key, value]) => {
      projectInfo.milestones[Number(key)].payments.forEach(({ ...rest}, idx, orig) => {
        orig[idx] = { ...rest, id: rest.id * -1 }
      })

      // console.log(projectInfo.milestones[Number(key)].payments)
    })
  }

  return (
    <CreateProject
      isEditMode={Boolean(props.isEditMode)}
      isCopyMode={Boolean(props.isCopyMode)}
      draftId={props.isEditMode || props.isCopyMode ? undefined : props.draftId}
      isSubProject={Boolean(props.isSubProject)}
      defaultInputs={projectInfo}
      allTasks={tasks}
      projectCategories={projectCategories}
      taskTemplates={taskTemplates}
      teamLeads={filteredTeamLeads}
      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;
