import { useMutation, useQuery } from "@tanstack/react-query";

import { EmployeeWithUnitListResponse, UserWithUnitListResponse } from "../dto/employees/employees";
import { EmployeeQueryParams, employeeService } from "../services/api/employeesService";
import { getEmployeesUnderOrg } from "@/shared/services/organizationsService";

export const useEmployees = ({
  unitId,
  organizationId,
  params,
}: {
  unitId?: string;
  organizationId?: string;
  params?:EmployeeQueryParams;
}) => {
  const {
    data: employeesResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery<UserWithUnitListResponse>({
    queryKey: ["employees", unitId],
    queryFn: async () => {
      const { data } = await employeeService.getUsersWithUnitById(unitId!, {
        take: 3000,
      });
      return data;
    },
    enabled: !!unitId,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const {
    data: employeesResponseByOrg,
    isLoading: isLoadingEmployeesByOrg,
    isError: isErrorEmployeesByOrg,
    refetch: refetchEmployeesByOrg,
  } = useQuery<EmployeeWithUnitListResponse | UserWithUnitListResponse>({
    queryKey: ["employees", organizationId, unitId, params],
    queryFn: async () => {
      // If unitId is selected, use the active-with-unit endpoint
      if (unitId) {
        const { data } = await employeeService.getUsersWithUnitById(unitId, params || {});
        return data;
      }
      // Otherwise use the by-organization endpoint
      const { data } = await getEmployeesUnderOrg(
        organizationId!,
        params
      );
      return data;
    },
    enabled: !!(organizationId || unitId),
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const { mutate: getEmployeeDetails, isPending: isFetchingEmployee } =
    useMutation({
      mutationFn: async (id: string) => {
        const { data } = await employeeService.getEmployee(id);
        return data;
      },
    });

  // Normalize the response to always have a consistent structure
  const normalizedEmployeesResponseByOrg = employeesResponseByOrg
    ? {
        count: employeesResponseByOrg.count,
        items: employeesResponseByOrg.items.map((item: any) => {
          // If the item already has a user property, it's EmployeeWithUnitDto
          if ('user' in item && item.user) {
            return item;
          }
          // If not, wrap it as UserDTO in the user property for consistency
          return {
            id: item.id,
            user: item,
            employeePositions: item.employeePositions || [],
          };
        }),
      }
    : undefined;

  return {
    employeesResponse,
    isLoading,
    isError,
    refetch,
    getEmployeeByDetails: getEmployeeDetails,
    isFetchingEmployee,
    refetchEmployeesByOrg,
    isErrorEmployeesByOrg,
    isLoadingEmployeesByOrg,
    employeesResponseByOrg: normalizedEmployeesResponseByOrg,
  };
};
