import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import {
  approvePendingEmployees,
  fetchCurrentEmployees,
  rejectPendingEmployees,
  Params,
} from "@/record-management/services/api/employeesService";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export enum EUserStatus {
  PENDING = "pending",
  ADJUSTED = "adjusted",
  SUBMITTED = "submitted",
  ACCEPTED = "accepted",
  REJECTED = "rejected",
}

const FIVE_MIN = 5 * 60 * 1000;

export const usePendingUsers = (params: Params) => {
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId ?? null;
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // Fetch pending users
  const {
    data: pendingUsers = { count: 0, items: [] },
    isLoading: loadingPendingUsers,
    error: pendingUsersError,
  } = useQuery({
    queryKey: ["pendingEmployees", unitId, params],
    queryFn: () =>
      fetchCurrentEmployees(
        { ...params, userStatus: EUserStatus.PENDING },
        unitId!
      ),
    enabled: !!unitId,
    staleTime: FIVE_MIN,
  });

  // Approve mutation with toast notifications
  const approveMutation = useMutation({
    mutationFn: async (id: string) => {
      if (!id) throw new Error("Employee ID is missing");
      await approvePendingEmployees(id);
    },
    onSuccess: () => {
      toast.success("Employee approved successfully");
      queryClient.invalidateQueries({ queryKey: ["pendingEmployees"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Reject mutation with toast notifications
  const rejectMutation = useMutation({
    mutationFn: async (id: string) => {
      if (!id) throw new Error("Employee ID is missing");
      await rejectPendingEmployees(id);
    },
    onSuccess: () => {
      toast.success("Employee rejected successfully");
      queryClient.invalidateQueries({ queryKey: ["pendingEmployees"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    pendingUsers,
    loadingPendingUsers,
    pendingUsersError,
    approveMutation,
    rejectMutation,
  };
};