import { useEffect, useState } from "react";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import { RolesRepository } from "../repositories/MastersRepository";
import EmployeeRepository from "../repositories/EmployeeRepository";
import ProjectRepository from "../repositories/ProjectRepository";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import { useSelector } from "react-redux";
import { store } from "../store/store";
import { queryClient } from "../layouts/AuthLayout";

// Query ---------------------------------------------------------------------------

export const useAllEmployees = (showInactive) => {
  const {
    data = [],
    isLoading,
    error,
    refetch, // optional if you want recall functionality
  } = useQuery({
    queryKey: ["allEmployee", showInactive],
    queryFn: async () => {
      const res = await EmployeeRepository.getAllEmployeeList(showInactive);
      return res.data;
    },
  });

  return {
    employeesList: data,
    loading: isLoading,
    error,
    recallEmployeeData: refetch,
  };
};

//  ManageBucket.jsx
export const useEmployees = (selectedProject) => {
  const {
    data = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["employeeListByProject", selectedProject],
    queryFn: async () => {
      const res = await EmployeeRepository.getEmployeeListByproject(
        selectedProject
      );
      return res.data || res;
    },
    enabled: !!selectedProject,
  });

  return {
    employees: data,
    loading: isLoading,
    projects: [], // if needed, pass this separately or manage from another hook
    reCallAllEmployee: refetch,
    error,
  };
};

// ManageRole.jsx
export const useEmployeeRoles = (employeeId) => {
  const {
    data = [],
    isLoading: loading,
    error,
  } = useQuery({
    queryKey: ["employeeRoles", employeeId],
    queryFn: async () => {
      const res = await RolesRepository.getEmployeeRoles(employeeId);
      return res.data;
    },
    enabled: !!employeeId,
  });

  return {
    employeeRoles: data,
    loading,
    error,
  };
};

// EmployeeProfile.jsx
export const useEmployeesByProject = (projectId) => {
  const {
    data = [],
    isLoading: loading,
    error,
    refetch: recallProjectEmplloyee,
  } = useQuery({
    queryKey: ["projectEmployees", projectId],
    queryFn: async () => {
      const res = await ProjectRepository.getEmployeesByProject(projectId);
      return res.data;
    },
    enabled: !!projectId,
  });

  return {
    employees: data,
    loading,
    error,
    recallProjectEmplloyee,
  };
};

// EmployeeList.jsx
export const useEmployeesAllOrByProjectId = (
  showAllEmployees,
  projectId,
  showInactive
) => {
  const queryKey = showAllEmployees
    ? ["allEmployees", showInactive]
    : ["projectEmployees", projectId, showInactive];

  const queryFn = async () => {
    if (showAllEmployees) {
      const res = await EmployeeRepository.getAllEmployeeList(showInactive);
      return res.data;
    } else {
      if (!projectId) return [];
      const res = await EmployeeRepository.getEmployeeListByproject(projectId);
      return res.data;
    }
  };

  const {
    data: employees = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey,
    queryFn,
    enabled:
      typeof showInactive === "boolean" && (showAllEmployees || !!projectId),
  });

  return {
    employees,
    loading: isLoading,
    error,
    recallEmployeeData: refetch,
  };
};

//  ManageEmployee.jsx
export const useEmployeeProfile = (employeeId) => {
  const isEnabled = !!employeeId;
  const {
    data = null,
    isLoading: loading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["employeeProfile", employeeId],
    queryFn: async () => {
      if (!employeeId) return null;
      const res = await EmployeeRepository.getEmployeeProfile(employeeId);
      return res.data;
    },
    enabled: isEnabled,
  });

  return {
    employee: data,
    loading,
    error,
    refetch,
  };
};

export const useEmployeesName = (projectId, search) => {
  return useQuery({
    queryKey: ["employees", projectId, search],
    queryFn: async() => await EmployeeRepository.getEmployeeName(projectId, search),
   
    staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes
  });
};

export const useEmployeesNameByProject = (projectId) => {
  return useQuery({
    queryKey: ["Projectemployees", projectId],
    queryFn: async () => {
      const response = await EmployeeRepository.getEmployeeName(projectId);
      return response?.data || []; // handle undefined/null response
    },
    enabled: !!projectId, // only fetch if projectId is truthy
    staleTime: 5 * 60 * 1000, // cache for 5 minutes
  });
};


// Mutation------------------------------------------------------------------

export const useUpdateEmployee = () => {
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (employeeData) =>
      EmployeeRepository.manageEmployee(employeeData),
    onSuccess: (_, variables) => {
      const id = variables.id || variables.employeeId;
      const isAllEmployee = variables.IsAllEmployee;

      // Cache invalidation
      queryClient.invalidateQueries({ queryKey: ["allEmployees"] });
      // queryClient.invalidateQueries(['employeeProfile', id]);
      queryClient.invalidateQueries({ queryKey: ["projectEmployees"] });
      queryClient.removeQueries({ queryKey: ["empListByProjectAllocated"] });

      // queryClient.invalidateQueries( {queryKey:[ 'employeeListByProject']} );
      showToast(
        `Employee ${id ? "updated" : "created"} successfully`,
        "success"
      );
    },
    onError: (error) => {
      const msg =
        error?.response?.data?.message ||
        error.message ||
        "Something went wrong";
      showToast(msg, "error");
    },
  });
};

export const useSuspendEmployee = ({
  setIsDeleteModalOpen,
  setemployeeLodaing,
}) => {
  const queryClient = useQueryClient();
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  return useMutation({
    mutationFn: (id) => {
      setemployeeLodaing(true);
      return EmployeeRepository.deleteEmployee(id);
    },

    onSuccess: () => {
      // queryClient.invalidateQueries( ['allEmployee',false]);
      queryClient.invalidateQueries({ queryKey: ["projectEmployees"] });
      queryClient.invalidateQueries({
        queryKey: ["employeeListByProject", selectedProject],
      });
      showToast("Employee deleted successfully.", "success");
      setIsDeleteModalOpen(false);
    },

    onError: (error) => {
      const message =
        error.response?.data?.message ||
        error.message ||
        "An unexpected error occurred";
      showToast(message, "error");
      setIsDeleteModalOpen(false);
    },

    onSettled: () => {
      setemployeeLodaing(false);
    },
  });
};

// Manage Role

export const useUpdateEmployeeRoles = ({
  onClose,
  resetForm,
  onSuccessCallback,
} = {}) => {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (updates) => RolesRepository.createEmployeeRoles(updates),
    onSuccess: () => {
      showToast("Roles updated successfully", "success");

      resetForm?.();
      onClose?.();
      onSuccessCallback?.();

      queryClient.invalidateQueries({ queryKey: ["employeeRoles"] });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onError: (err) => {
      const message =
        err?.response?.data?.message ||
        err?.message ||
        "Error occurred while updating roles";
      showToast(message, "error");
    },
  });

  return {
    updateRoles: mutation.mutate,
    isPending: mutation.isPending,
    isError: mutation.isError,
    error: mutation.error,
  };
};
