import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  activateUser,
  AssignEmployeePayload,
  assignEmployees,
  assignFirstsForSecond,
  assignSecondsForFirst,
  deactivateUser,
  deleteEmployeePosition,
  EmployeePositionQueryParams,
  getGivenFirst,
  getGivenSecond,
  InactiveEPPayload,
  inviteEmployeePosition,
  removeFirstsForSecond,
  removeSecondsForFirst,
  setInactive,
} from "../services/api/employeePositionsService";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export const useEmployeePositions = (params?: EmployeePositionQueryParams) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // --- Queries ---
  const getGivenFirstQuery = (id: string) =>
    useQuery({
      queryKey: ["positionEmployees", "given-first", id],
      queryFn: () => getGivenFirst(id, params).then((res) => res.data),
      enabled: !!id,
    });

  const getGivenSecondQuery = (id: string) =>
    useQuery({
      queryKey: ["positionEmployees", "given-second", id],
      queryFn: () => getGivenSecond(id, params).then((res: any) => res.data),
      enabled: !!id,
    });

  // --- Mutations ---
  const invite = useMutation({
    mutationFn: ({
      payload,
      successCallback,
    }: {
      payload: any;
      successCallback: () => void;
    }) => inviteEmployeePosition(payload),

    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] });
      variables.successCallback();
    },

    onError: (error) => {
      handleError(error);
    },
  });

    const deactivate = useMutation({
      mutationFn: ({
        payload,
        successCallback,
      }: {
        payload: string;
        successCallback: () => void;
      }) => deactivateUser(payload),

      onSuccess: (_data, variables) => {
        queryClient.invalidateQueries({ queryKey: ["deleteEmployees"] });
        queryClient.invalidateQueries({ queryKey: ["positionEmployees"] });
      queryClient.invalidateQueries({ queryKey: ["employees"] });


        variables.successCallback();
      },

      onError: (error) => {
        handleError(error);
      },
    });
        const activate = useMutation({
          mutationFn: ({
            payload,
            successCallback,
          }: {
            payload: string;
            successCallback: () => void;
          }) => activateUser(payload),

          onSuccess: (_data, variables) => {
            queryClient.invalidateQueries({ queryKey: ["archived-users"] });
      queryClient.invalidateQueries({ queryKey: ["employees"] });

            variables.successCallback();
          },

          onError: (error) => {
            handleError(error);
          },
        });

  const setInactiveMutation = useMutation({
    mutationFn: ({
      payload,
      successCallback,
    }: {
      payload: InactiveEPPayload;
      successCallback: () => void;
    }) => setInactive(payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] });
      toast.success("Team member removed successfully.");
      variables.successCallback();
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const assignFirstsForSecondMutation = useMutation({
    mutationFn: (payload: any) => assignFirstsForSecond(payload),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] }),
  });

  const assignSecondsForFirstMutation = useMutation({
    mutationFn: (payload: any) => assignSecondsForFirst(payload),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] }),
  });

  const assignEmployeeForPosition = useMutation({
    mutationFn: (payload: AssignEmployeePayload) => assignEmployees(payload),
    onSuccess: () =>{
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] });
      queryClient.invalidateQueries({ queryKey: ["employees"] });
},
    onError: (error) => {
      handleError(error);
    },
  });

  const removeFirstsForSecondMutation = useMutation({
    mutationFn: (payload: any) => removeFirstsForSecond(payload),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] }),
  });

  const removeSecondsForFirstMutation = useMutation({
    mutationFn: (payload: any) => removeSecondsForFirst(payload),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] }),
  });

  const remove = useMutation({
    mutationFn: (id: string) => deleteEmployeePosition(id),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["positionEmployees"] }),
  });

  // --- Return exposed mutateAsync and query helpers ---
  return {
    getGivenFirstQuery,
    getGivenSecondQuery,
    invite: invite.mutateAsync,
    isInviting: invite.isPending,
    setInactive: setInactiveMutation.mutateAsync,
    isDeActivatingUser: setInactiveMutation.isPending,
    assignFirstsForSecond: assignFirstsForSecondMutation.mutateAsync,
    assignSecondsForFirst: assignSecondsForFirstMutation.mutateAsync,
    removeFirstsForSecond: removeFirstsForSecondMutation.mutateAsync,
    assignEmployee: assignEmployeeForPosition.mutateAsync,
    isAssigning: assignEmployeeForPosition.isPending,
    removeSecondsForFirst: removeSecondsForFirstMutation.mutateAsync,
    remove: remove.mutateAsync,
    deactivateUser: deactivate.mutateAsync,
    isDeactivating: deactivate.isPending,
    activateUser: activate.mutateAsync,
    isActivatingUser: activate.isPending,
  };
};
