import { create } from "zustand";
import { persist } from "zustand/middleware";
import { type ExamPhase } from "../types/sheet";
import type { SessionModuleQuestions } from "../types/session";
import type { Results } from "../types/test";

interface SatExamState {
  currentModuleQuestions: SessionModuleQuestions | null;
  phase: ExamPhase;
  questionIndex: number;
  endTime: number | null;
  results: Results | null;

  setModuleQuestions: (module: SessionModuleQuestions) => void;
  startExam: () => void;
  nextQuestion: () => void;
  prevQuestion: () => void;
  goToQuestion: (index: number) => void;

  setPhase: (phase: ExamPhase) => void;

  startBreak: () => void;
  skipBreak: () => void;
  finishExam: () => void;
  quitExam: () => void;
  resetExam: () => void;
  setResults: (results: Results) => void;
  getRemainingTime: () => number;
}

const BREAK_DURATION = 600; // seconds

export const useSatExam = create<SatExamState>()(
  persist(
    (set, get) => ({
      currentModuleQuestions: null,
      phase: "IDLE",
      questionIndex: 0,
      endTime: null,
      results: null,

      setModuleQuestions: (module: SessionModuleQuestions) => {
        const endTime = Date.now() + module.time_limit_minutes * 1000;

        set({
          currentModuleQuestions: module,
          questionIndex: 0,
          endTime,
        });
      },

      startExam: () => {
        set({ phase: "MODULE", questionIndex: 0 });
      },

      nextQuestion: () => {
        const { currentModuleQuestions, questionIndex } = get();
        const questions = currentModuleQuestions?.questions ?? [];

        if (questionIndex < questions.length - 1) {
          set({ questionIndex: questionIndex + 1 });
        }
      },

      prevQuestion: () => {
        const { questionIndex } = get();
        if (questionIndex > 0) {
          set({ questionIndex: questionIndex - 1 });
        }
      },

      goToQuestion: (index: number) =>
        set((state) => {
          const total = state.currentModuleQuestions?.questions.length ?? 0;

          if (index < 0 || index >= total) return state;

          return { questionIndex: index };
        }),

      startBreak: () => {
        const endTime = Date.now() + BREAK_DURATION * 1000;

        set((state) => ({
          phase: "BREAK",
          endTime,
          questionIndex: 0, // optional: reset question index for next module UX
        }));
      },

      skipBreak: () => {
        const module = get().currentModuleQuestions;

        if (!module) return;

        const endTime = Date.now() + module.time_limit_minutes * 1000;

        set({
          phase: "MODULE",
          endTime,
          questionIndex: 0,
        });
      },

      finishExam: () => set({ phase: "FINISHED", endTime: null }),
      quitExam: () => set({ phase: "QUIT", endTime: null }),

      setPhase: (phase) => {
        set({ phase: phase });
      },

      setResults: (results: Results) => set({ results }),

      getRemainingTime: () => {
        const { endTime } = get();
        if (!endTime) return 0;
        return Math.max(0, Math.floor((endTime - Date.now()) / 1000));
      },

      resetExam: () =>
        set({
          currentModuleQuestions: null,
          phase: "IDLE",
          questionIndex: 0,
          endTime: null,
          results: null, // reset results too
        }),
    }),
    {
      name: "sat-exam-storage",
      partialize: (state) => ({
        // Only persist things you want to survive reloads
        currentModuleQuestions: state.currentModuleQuestions,
        phase: state.phase,
        questionIndex: state.questionIndex,
        endTime: state.endTime,
        // Notice: results is NOT included
      }),
    },
  ),
);
