import { useEffect, useRef } from "react";
import { useAuth } from "@/shared/context/AuthContext";
import { useAuthUser } from "./useAuthUser";
import Cookies from "js-cookie";
import { toast } from "sonner";

/**
 * Hook to monitor delegation period and auto-logout when delegation is active
 * - Delegatee: logged out when delegation ends
 * - Delegator: logged out during the entire delegation period (cannot access while delegating)
 */
export const useDelegationMonitor = () => {
  const { user, setUser } = useAuth();
  const { logout } = useAuthUser();
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const hasShownWarningRef = useRef(false);

  useEffect(() => {
    // Check if user has delegation info in their data
    const checkDelegationStatus = () => {
      try {
        const authUserCookie = Cookies.get("auth-user");
        if (!authUserCookie) return;

        const userData = JSON.parse(authUserCookie);

        // Check if user is a delegatee (has delegationEndDate)
        const delegationEndDate = userData?.delegationEndDate;

        // Check if user is a delegator (has delegationStartDate and delegationEndDate)
        const delegationStartDate = userData?.delegationStartDate;

        // If no delegation info, clear interval
        if (!delegationEndDate && !delegationStartDate) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
          }
          hasShownWarningRef.current = false;
          return;
        }

        const currentTime = new Date().getTime();
        let shouldLogout = false;
        let logoutReason = "";

        // Check delegatee status (delegation end date)
        if (delegationEndDate) {
          const endTime = new Date(delegationEndDate).getTime();
          const timeRemaining = endTime - currentTime;

          if (timeRemaining <= 0) {
            shouldLogout = true;
            logoutReason =
              "Your delegation period has ended. You have been logged out.";
          } else {
            // Show warning 5 minutes before delegation ends
            const warningThreshold = 5 * 60 * 1000; // 5 minutes in milliseconds
            if (
              timeRemaining <= warningThreshold &&
              !hasShownWarningRef.current
            ) {
              hasShownWarningRef.current = true;
              const minutesRemaining = Math.floor(timeRemaining / 60000);

              toast.warning("Delegation Ending Soon", {
                description: `Your delegation will end in ${minutesRemaining} minute(s). You will be logged out automatically.`,
                duration: 10000,
              });
            }
          }
        }

        // Check delegator status (delegation start date - delegator cannot access during delegation)
        if (delegationStartDate && !shouldLogout) {
          const startTime = new Date(delegationStartDate).getTime();
          const endTime = delegationEndDate
            ? new Date(delegationEndDate).getTime()
            : startTime;

          // If current time is between start and end, delegator should be logged out
          if (currentTime >= startTime && currentTime <= endTime) {
            shouldLogout = true;
            logoutReason =
              "Your delegation is currently active. You cannot access the system during this period.";
          }
        }

        // If delegation has ended or delegator is in delegation period, logout immediately
        if (shouldLogout) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
          }

          toast.error("Delegation Period Active", {
            description: logoutReason,
          });

          // Perform logout
          logout();
          return;
        }
      } catch (error) {
        console.error("Error checking delegation status:", error);
      }
    };

    // Check immediately on mount
    checkDelegationStatus();

    // Set up interval to check every 10 seconds for more responsive monitoring
    intervalRef.current = setInterval(checkDelegationStatus, 10000);

    // Handle page visibility - check when user returns to tab
    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        checkDelegationStatus();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

    // Cleanup on unmount
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [user, logout, setUser]);
};
