import { Module } from '@/interfaces';
import useExamStore from '@/stores/exam';
import { useEffect, useRef } from 'react';

const useExamTimer = (module: Module, disabled: boolean = false) => {
  const { dispatch, saveSession, timeSpent, inactivity } = useExamStore();

  const initialTimeSpentRef = useRef(timeSpent);
  const initialInactivityRef = useRef(inactivity);

  const timeSpentRef = useRef(0);
  const inactivityTimerRef = useRef(0);
  const totalInactivityRef = useRef(0);

  const resetInactivityTimer = () => {
    if (inactivityTimerRef.current >= 120) {
      totalInactivityRef.current += inactivityTimerRef.current;
    }
    inactivityTimerRef.current = 0;
  };

  useEffect(() => {
    if (!disabled) {
      const timerInterval = setInterval(() => {
        timeSpentRef.current += 1;

        if (timeSpentRef.current % 20 === 0) {
          dispatch({
            type: "UPDATE_TIMERS",
            payload: {
              timeSpent: initialTimeSpentRef.current + timeSpentRef.current,
              inactivity: initialInactivityRef.current + totalInactivityRef.current,
              timeSpentCurrentModule: timeSpentRef.current
            }
          });
          if (module !== "speaking") {
            saveSession().catch(error => {
              console.error('Failed to save session:', error);
            });
          }
        }

      }, 1000);

      return () => clearInterval(timerInterval);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, disabled, saveSession, module]);

  useEffect(() => {
    if (!disabled) {
      const inactivityInterval = setInterval(() => {
        inactivityTimerRef.current += 1;
      }, 1000);

      return () => clearInterval(inactivityInterval);
    }
  }, [disabled]);

  useEffect(() => {
    if (!disabled) {
      document.addEventListener("keydown", resetInactivityTimer);
      document.addEventListener("mousemove", resetInactivityTimer);
      document.addEventListener("mousedown", resetInactivityTimer);

      return () => {
        document.removeEventListener("keydown", resetInactivityTimer);
        document.removeEventListener("mousemove", resetInactivityTimer);
        document.removeEventListener("mousedown", resetInactivityTimer);
      };
    }
  }, [disabled]);

  const updateTimers = () => {
    if (!disabled) {
      dispatch({
        type: "UPDATE_TIMERS",
        payload: {
          timeSpent: initialTimeSpentRef.current + timeSpentRef.current,
          inactivity: initialInactivityRef.current + totalInactivityRef.current,
          timeSpentCurrentModule: 0
        }
      });
    }
  };

  return updateTimers;
};

export default useExamTimer;