'use client';

import { useEffect } from 'react';
import { ExamState } from '@/contexts/ExamContext';

interface PersistedExamState {
  examId: string;
  currentQuestion: number;
  answers: Record<number, number>;
  flaggedQuestions: number[];
  timeRemaining: number;
  startTime: number;
}

const STORAGE_KEY = 'exam_session';

export function useExamPersistence(
  examId: string | undefined,
  state: ExamState,
  dispatch: React.Dispatch<any>
) {
  // Load persisted state on mount
  useEffect(() => {
    if (!examId) return;

    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const persistedState: PersistedExamState = JSON.parse(stored);
        
        // Only restore if it's the same exam
        if (persistedState.examId === examId) {
          // Check if session is still valid (not expired)
          const now = Date.now();
          const sessionAge = (now - persistedState.startTime) / 1000; // in seconds
          
          if (sessionAge < persistedState.timeRemaining + 300) { // 5 minutes grace period
            // Restore state
            dispatch({ type: 'SET_CURRENT_QUESTION', payload: persistedState.currentQuestion });
            
            // Restore answers
            Object.entries(persistedState.answers).forEach(([questionIndex, answer]) => {
              dispatch({ 
                type: 'SET_ANSWER', 
                payload: { questionIndex: parseInt(questionIndex), answer } 
              });
            });
            
            // Restore flagged questions
            persistedState.flaggedQuestions.forEach(questionIndex => {
              dispatch({ type: 'TOGGLE_FLAG', payload: questionIndex });
            });
            
            // Calculate remaining time based on elapsed time
            const adjustedTimeRemaining = Math.max(0, persistedState.timeRemaining - sessionAge);
            // Note: Time will be set by the exam data, but we can adjust it here if needed
          } else {
            // Session expired, clear storage
            localStorage.removeItem(STORAGE_KEY);
          }
        }
      }
    } catch (error) {
      console.error('Failed to load persisted exam state:', error);
      localStorage.removeItem(STORAGE_KEY);
    }
  }, [examId, dispatch]);

  // Save state to localStorage whenever it changes
  useEffect(() => {
    if (!examId || !state.examData || state.isSubmitted) {
      // Clear storage if exam is submitted or not started
      localStorage.removeItem(STORAGE_KEY);
      return;
    }

    try {
      const persistedState: PersistedExamState = {
        examId,
        currentQuestion: state.currentQuestion,
        answers: state.answers,
        flaggedQuestions: Array.from(state.flaggedQuestions),
        timeRemaining: state.timeRemaining,
        startTime: Date.now() - ((state.examData.duration * 60) - state.timeRemaining) * 1000,
      };

      localStorage.setItem(STORAGE_KEY, JSON.stringify(persistedState));
    } catch (error) {
      console.error('Failed to persist exam state:', error);
    }
  }, [
    examId,
    state.currentQuestion,
    state.answers,
    state.flaggedQuestions,
    state.timeRemaining,
    state.examData,
    state.isSubmitted,
  ]);

  // Clear storage when component unmounts or exam is submitted
  useEffect(() => {
    return () => {
      if (state.isSubmitted) {
        localStorage.removeItem(STORAGE_KEY);
      }
    };
  }, [state.isSubmitted]);

  // Clear storage function for manual cleanup
  const clearPersistedState = () => {
    localStorage.removeItem(STORAGE_KEY);
  };

  return { clearPersistedState };
}

// Utility function to check if there's a persisted exam session
export function hasPersistedExamSession(examId: string): boolean {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      const persistedState: PersistedExamState = JSON.parse(stored);
      return persistedState.examId === examId;
    }
  } catch (error) {
    console.error('Failed to check persisted exam session:', error);
  }
  return false;
}

// Utility function to get persisted exam info
export function getPersistedExamInfo(examId: string): PersistedExamState | null {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      const persistedState: PersistedExamState = JSON.parse(stored);
      if (persistedState.examId === examId) {
        return persistedState;
      }
    }
  } catch (error) {
    console.error('Failed to get persisted exam info:', error);
  }
  return null;
}