import { useQueries, useQuery } from "@tanstack/react-query";
import {
  fetchAllInternalDepartments,
  fetchAssignedScopeDepartments,
  fetchCurrentDepartment,
  fetchInternalDepartments,
  fetchImmediateChildDepartments,
  fetchInternalReceivingDepartments,
  fetchScopedDepartments,
  fetchScopedEmployees,
} from "@/record-management/services/api/departmentService";
import {
  fetchModifiedValidOrganization,
  fetchUnitById,
  fetchValidOrganization,
} from "@/record-management/services/api/organizationService";
import { fetchRecordTypes } from "@/record-management/services/api/recordTypesService";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import {
  fetchCurrentEmployees,
  fetchRecordReceivingEmployees,
} from "@/record-management/services/api/employeesService";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { Params } from "@/user-management/services/api/positionTypesService";

const FIVE_MIN = 5 * 60 * 1000;

const useSettings = (params?: Params) => {
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId ?? null;
  const take = 300;
  const skip = 0;
  /* ───────────────── Organizations ───────────────── */
  const {
    data: orgsResponse,
    isLoading: loadingOrgs,
    error: orgsError,
  } = useQuery({
    queryKey: ["organizations", { take: 50, skip: 0 }], // include param
    queryFn: fetchValidOrganization,
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });
  const {
    data: orgsModifiedResponse,
    isLoading: loadingModifiedOrgs,
    error: orgsModifiedError,
  } = useQuery({
    queryKey: ["organizationsModified", { take: 50, skip: 0 }], // include param
    queryFn: fetchModifiedValidOrganization,
    staleTime: FIVE_MIN,
  });
  const {
    data: exteranlOrgsResponse,
    isLoading: loadingExternalOrgs,
    error: externalOrgsError,
  } = useQuery({
    queryKey: ["organizations"], // include param
    queryFn: fetchValidOrganization,
    staleTime: FIVE_MIN,
  });
  /* ───────────────── Departments (internal) ───────────────── */
  const {
    data: deptResponse,
    isLoading: loadingDepts,
    error: deptsError,
  } = useQuery({
    queryKey: ["departments"],
    queryFn: () => fetchInternalReceivingDepartments(),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });

  /* ───────────────── Record Types (tenant-wide) ───────────────── */
  const {
    data: recordTypesResponse,
    isLoading: loadingRecordTypes,
    error: recordTypesError,
  } = useQuery({
    queryKey: ["record-types"],
    queryFn: fetchRecordTypes,
    staleTime: FIVE_MIN,
  });
  /* ───────────────── Current Employees ───────────────── */
  const {
    data: allDeptResponse,
    isLoading: loadingAllDepts,
    error: AllDeptsError,
  } = useQuery({
    queryKey: ["departments"],
    queryFn: () =>
      fetchInternalReceivingDepartments({
        take: 1000, // Adjust as needed
        skip: 0,
      }),

    staleTime: FIVE_MIN,
    enabled: !!unitId,
  });
  const {
    data: allScopedDeptResponse,
    isLoading: loadingAllScopedDepts,
    error: AllScopedDeptsError,
  } = useQuery({
    queryKey: ["scoped-departments"],
    queryFn: () =>
      fetchScopedDepartments({
        take: 1000, // Adjust as needed
        skip: 0,
      }),

    staleTime: FIVE_MIN,
    enabled: !!unitId,
  });
  const {
    data: departmentsForAssign,
    isLoading: loadingdepartmentsForAssign,
    error: departmentsForAssignError,
  } = useQuery({
    queryKey: ["assigned-departments"],
    queryFn: () =>
      fetchAssignedScopeDepartments({
        take: 1000, // Adjust as needed
        skip: 0,
      }),

    staleTime: FIVE_MIN,
    enabled: !!unitId,
  });
  /* ───────────────── Scopeed Employees ───────────────── */
  const {
    data: allScopedEmployeeResponse,
    isLoading: loadingAllScopedEmployees,
    error: AllScopedEmployeesError,
  } = useQuery({
    queryKey: ["scoped-Employees"],
    queryFn: () =>
      fetchScopedEmployees({
        take: 1000, // Adjust as needed
        skip: 0,
      }),

    staleTime: FIVE_MIN,
    enabled: !!unitId,
  });
  /* ───────────────── Current Department ───────────────── */
  const {
    data: positionResponse,
    isLoading: loadingPosition,
    error: positionError,
  } = useQuery({
    queryKey: ["current-department", unitId],
    queryFn: () => fetchCurrentDepartment(unitId!),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });
  /*-----------------------employees-------------/
  /* ───────────────── Current Employees ───────────────── */
  const {
    data: employeesResponse,
    isLoading: loadingEmployees,
    error: employeesError,
  } = useQuery({
    queryKey: ["current-employees", unitId, take, skip],
    queryFn: () => fetchCurrentEmployees({ take, skip }, unitId!),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });

  const {
    data: currentEmployeesResponse,
    isLoading: loadingCurrentEmployees,
    error: CurrentEmployeesError,
  } = useQuery({
    queryKey: ["current-employees", unitId],
    queryFn: () => fetchRecordReceivingEmployees({ take, skip }, unitId!),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });
  const { data: countData } = useQuery({
    queryKey: ["all-departments-count", unitId],
    queryFn: () => fetchAllInternalDepartments(unitId!, { take: 1, skip: 0 }),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });

  const totalCount = countData?.count ?? 0;

  // Second query: fetch all using real count
  const {
    data: allPostionList,
    isLoading: loadingPositionList,
    error: allPostionListError,
  } = useQuery({
    queryKey: ["postion-list", unitId],
    queryFn: () => fetchAllInternalDepartments(unitId!, { take, skip }),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });
  const {
    data: allDepratments,
    isLoading: loadingallDepratments,
    error: allDepratmentsError,
  } = useQuery({
    queryKey: ["all-departments", unitId, totalCount],
    queryFn: () =>
      fetchAllInternalDepartments(unitId!, { take: totalCount, skip: 0 }),
    enabled: !!unitId && totalCount > 0,
    staleTime: FIVE_MIN,
  });
  /*--------- Departmenst (immediate child) ----- */
  const {
    data: immedateChildResponse,
    isLoading: loadingImmedateChildDepts,
    error: deptsImmedateChildError,
  } = useQuery({
    queryKey: ["immediate-departments"],
    queryFn: () => fetchImmediateChildDepartments(),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });

  return {
    /* raw lists */
    allOrgs: orgsResponse?.items ?? [],
    allModifiedOrgs: orgsModifiedResponse ?? [],
    allDepartmentUnits: deptResponse?.items ?? [],
    listPositionResponse: positionResponse,
    alluser: employeesResponse?.items ?? [],
    listAllDepartmentResponse: allDeptResponse?.items ?? [],
    allExternalOrgs: exteranlOrgsResponse?.items ?? [],
    allScopedDepartments: allScopedDeptResponse?.items ?? [],
    allScopedEmployees: allScopedEmployeeResponse?.items ?? [],
    allPostionList: allPostionList?.items ?? [],
    immedateChildResponse: immedateChildResponse?.items ?? [],
    allValidDepartments: departmentsForAssign?.items ?? [],
    allDepratments: allDepratments?.items ?? [],
    allDepartmentsCount: allDepratments?.count,

    /* lookup tables */
    recordTypes: recordTypesResponse?.items ?? [],

    employeesResponse,
    currentEmployeesResponse,

    /* loading / error flags */
    isLoading:
      loadingOrgs ||
      loadingDepts ||
      loadingRecordTypes ||
      loadingPosition ||
      loadingEmployees ||
      loadingCurrentEmployees ||
      loadingAllDepts ||
      loadingExternalOrgs ||
      loadingAllScopedDepts ||
      loadingAllScopedEmployees ||
      loadingallDepratments ||
      loadingdepartmentsForAssign ||
      loadingImmedateChildDepts,

    error:
      orgsError ||
      deptsError ||
      recordTypesError ||
      positionError ||
      employeesError ||
      CurrentEmployeesError ||
      AllDeptsError ||
      externalOrgsError ||
      AllScopedDeptsError ||
      AllScopedEmployeesError ||
      allDepratmentsError ||
      departmentsForAssignError ||
      deptsImmedateChildError,
  };
};

export const useUnitsByIds = (unitIds: string[] | string | string[][]) => {
  // Flatten nested arrays and normalize to a flat array of strings
  const idsArray = Array.isArray(unitIds)
    ? unitIds.flat().map(String) // flatten and ensure all are strings
    : [unitIds];

  // Use useQueries for multiple IDs
  const queries = useQueries({
    queries: idsArray.map((id) => ({
      queryKey: ["unit", id],
      queryFn: () => fetchUnitById(id),
      enabled: !!id,
    })),
  });

  // Extract results
  const units: UnitDto[] = queries
    .filter((q) => !q.isLoading && !q.error && q.data)
    .map((q) => q.data as UnitDto);

  const isLoading = queries.some((q) => q.isLoading);
  const hasError = queries.some((q) => !!q.error);

  return { units, isLoading, hasError, queries };
};

export default useSettings;
