import { DelegatePositionResponse } from "@/record-management/dto/delegation/delegationDto";
import {
  delegatePosition,
  DelegatePositionPayload,
  deleteDelegations,
  EndDelegationPayload,
  myDelegationDetails,
  myDelegations,
  submitDelegations,
} from "@/record-management/services/api/employeePositionService";
import { updateDelegationRecord } from "@/record-management/services/api/userRecordService";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { MeDto } from "@/shared/dto/user/meDto";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import Cookies from "js-cookie";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

interface DelegationQueryParams {
  skip?: number;
  take?: number;
}

export const useDelegations = (params?: DelegationQueryParams) => {
  const { userDetails } = useAuthUser();
  const { permissionKeys, isLoading: userLoading } = useUserDetail(
    userDetails as MeDto,
  );
  const RO = permissionKeys.includes("can:dispatchRecords");
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const {
    data: delegationResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery<DelegatePositionResponse>({
    queryKey: ["delegations", params],
    queryFn: () => myDelegations(!RO ? params : {}),
    staleTime: 5 * 60 * 1000,
    enabled: !userLoading && !RO,
  });
  const {
    data: myDelegated,
    isLoading: isloadingDetail,
    isError: isErrorDetail,
    refetch: refetchDetail,
  } = useQuery<DelegatePositionResponse>({
    queryKey: ["delegationDetail", params],
    queryFn: () => myDelegationDetails(!RO ? params : {}),
    staleTime: 5 * 60 * 1000,
    enabled: !userLoading && !RO,
  });

  const delegateMutation = useMutation({
    mutationFn: (payload: DelegatePositionPayload) => delegatePosition(payload),
    onSuccess: (response: any) => {
      toast.success(t("msg.success"));

      // Store delegation start and end dates in auth cookie for monitoring
      if (response?.data?.startDate || response?.data?.endDate) {
        const authUserCookie = Cookies.get("auth-user");
        if (authUserCookie) {
          try {
            const userData = JSON.parse(authUserCookie);
            if (response.data.startDate) {
              userData.delegationStartDate = response.data.startDate;
            }
            if (response.data.endDate) {
              userData.delegationEndDate = response.data.endDate;
            }
            Cookies.set("auth-user", JSON.stringify(userData));
          } catch (error) {
            console.error(
              "Error updating auth cookie with delegation dates:",
              error,
            );
          }
        }
      }

      queryClient.invalidateQueries({ queryKey: ["delegations"] });
      queryClient.invalidateQueries({ queryKey: ["canDelegateStatus"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const deleteMutation = useMutation({
    mutationFn: ({
      id,
      ...payload
    }: { id: string } & EndDelegationPayload) =>
      deleteDelegations(id, payload),
    onSuccess: () => {
      // Clear delegation dates from auth cookie when delegation is deleted
      const authUserCookie = Cookies.get("auth-user");
      if (authUserCookie) {
        try {
          const userData = JSON.parse(authUserCookie);
          delete userData.delegationStartDate;
          delete userData.delegationEndDate;
          Cookies.set("auth-user", JSON.stringify(userData));
        } catch (error) {
          console.error(
            "Error clearing delegation dates from auth cookie:",
            error,
          );
        }
      }

      queryClient.invalidateQueries({ queryKey: ["delegations"] });
      queryClient.invalidateQueries({ queryKey: ["canDelegateStatus"] });
      // Hook-level toast fires reliably even if the calling modal has
      // already unmounted (per-call callbacks are dropped on unmount).
      toast.success(
        t(
          "delegation.terminatedSuccess",
          "Delegation terminated successfully",
        ),
      );
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const editmutation = useMutation({
    mutationFn: updateDelegationRecord,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegations"] });
      queryClient.invalidateQueries({ queryKey: ["delegationDetail"] });
      queryClient.invalidateQueries({ queryKey: ["canDelegateStatus"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const hasDelegated =
    (delegationResponse?.data?.filter(
      (pos: { isCurrent: boolean }) => pos.isCurrent,
    )?.length ?? 0) > 0;
  const hasbeenDelegated =
    (myDelegated?.data?.filter((pos: { isCurrent: boolean }) => pos.isCurrent)
      ?.length ?? 0) > 0;
  return {
    delegations: delegationResponse,
    isLoading,
    isError,
    refetch,
    delegatePosition: delegateMutation.mutate,
    mydelegated: myDelegated?.data,
    delegatePositionAsync: delegateMutation.mutateAsync,
    isDelegating: delegateMutation.isPending,
    deleteDelegation: deleteMutation.mutate,
    deleteDelegationAsync: deleteMutation.mutateAsync,
    editDelegation: editmutation.mutate,
    hasDelegated,
    hasbeenDelegated,
    myDelegated,
  };
};
