/**
 * 考试作答状态机 Hook（ai14）
 *
 * 状态流转：NotStarted → InProgress → AutoSaving → Submitting → Submitted
 * 防止非法状态转移，控制提交时机
 */

import { useReducer, useMemo } from "react";

export type ExamState =
  "NotStarted" | "InProgress" | "AutoSaving" | "Submitting" | "Submitted";

type ExamAction =
  | { type: "start" }
  | { type: "beginAutoSave" }
  | { type: "endAutoSave" }
  | { type: "beginSubmit" }
  | { type: "completeSubmit" };

/** 状态转移函数（纯函数，校验合法转移） */
function reducer(state: ExamState, action: ExamAction): ExamState {
  switch (action.type) {
    case "start":
      return state === "NotStarted" ? "InProgress" : state;
    case "beginAutoSave":
      return state === "InProgress" ? "AutoSaving" : state;
    case "endAutoSave":
      return state === "AutoSaving" ? "InProgress" : state;
    case "beginSubmit":
      return state === "InProgress" || state === "AutoSaving"
        ? "Submitting"
        : state;
    case "completeSubmit":
      return state === "Submitting" ? "Submitted" : state;
    default:
      return state;
  }
}

export interface UseExamStateMachineReturn {
  state: ExamState;
  actions: {
    start: () => void;
    beginAutoSave: () => void;
    endAutoSave: () => void;
    beginSubmit: () => void;
    completeSubmit: () => void;
  };
  canSubmit: boolean;
}

/** 考试作答状态机 */
export function useExamStateMachine(): UseExamStateMachineReturn {
  const [state, dispatch] = useReducer(reducer, "NotStarted");

  const actions = useMemo(
    () => ({
      start: () => dispatch({ type: "start" }),
      beginAutoSave: () => dispatch({ type: "beginAutoSave" }),
      endAutoSave: () => dispatch({ type: "endAutoSave" }),
      beginSubmit: () => dispatch({ type: "beginSubmit" }),
      completeSubmit: () => dispatch({ type: "completeSubmit" }),
    }),
    [],
  );

  const canSubmit = state === "InProgress" || state === "AutoSaving";

  return { state, actions, canSubmit };
}
