'use client';

import { useEffect, useRef, useCallback } from 'react';
import { signOut, useSession } from 'next-auth/react';

/**
 * Custom hook to automatically log out users after a period of inactivity
 * 
 * @param timeoutMs - Timeout in milliseconds (default: 2 hours = 7,200,000ms)
 * @param enabled - Whether the idle logout is enabled (default: true)
 */
export function useIdleLogout(timeoutMs: number = 2 * 60 * 60 * 1000, enabled: boolean = true) {
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const { data: session } = useSession();

  const resetTimer = useCallback(() => {
    // Clear existing timer
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    // Only set timer if user is logged in and hook is enabled
    if (session && enabled) {
      timerRef.current = setTimeout(() => {
        console.log('[IDLE_LOGOUT] User inactive for', timeoutMs / 1000 / 60, 'minutes, logging out...');
        signOut({ callbackUrl: '/' });
      }, timeoutMs);
    }
  }, [session, enabled, timeoutMs]);

  useEffect(() => {
    // Don't set up listeners if not enabled or no session
    if (!enabled || !session) {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      return;
    }

    // Events that indicate user activity
    const events = [
      'mousemove',
      'mousedown',
      'keydown',
      'scroll',
      'touchstart',
      'click',
      'keypress',
    ];

    // Add event listeners
    events.forEach((event) => {
      window.addEventListener(event, resetTimer, { passive: true });
    });

    // Initialize the timer
    resetTimer();

    // Cleanup function
    return () => {
      events.forEach((event) => {
        window.removeEventListener(event, resetTimer);
      });
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [session, enabled, resetTimer]);
}

