import { createContext, useContext, useState, ReactNode } from 'react';

export interface QuizQuestion {
  id: string;
  content: string;
  type: 'single' | 'multiple' | 'judgment' | 'text';
  options?: string[];
  answer: string | string[];
  analysis?: string;
  score: number;
  createdAt?: string;
  category?: string;
}

interface QuizContextType {
  questions: QuizQuestion[];
  setQuestions: (questions: QuizQuestion[]) => void;
  currentQuestionIndex: number;
  setCurrentQuestionIndex: (index: number) => void;
  answers: Record<string, string | string[]>;
  setAnswer: (questionId: string, answer: string | string[]) => void;
  setAnswers: (answers: Record<string, string | string[]>) => void;
  clearQuiz: () => void;
}

const QuizContext = createContext<QuizContextType | undefined>(undefined);

export const QuizProvider = ({ children }: { children: ReactNode }) => {
  const [questions, setQuestions] = useState<QuizQuestion[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<Record<string, string | string[]>>({});

  const setAnswer = (questionId: string, answer: string | string[]) => {
    setAnswers(prev => ({
      ...prev,
      [questionId]: answer
    }));
  };

  const clearQuiz = () => {
    setQuestions([]);
    setCurrentQuestionIndex(0);
    setAnswers({});
  };

  return (
    <QuizContext.Provider value={{
      questions,
      setQuestions,
      currentQuestionIndex,
      setCurrentQuestionIndex,
      answers,
      setAnswer,
      setAnswers,
      clearQuiz
    }}>
      {children}
    </QuizContext.Provider>
  );
};

export const useQuiz = () => {
  const context = useContext(QuizContext);
  if (!context) {
    throw new Error('useQuiz必须在QuizProvider内使用');
  }
  return context;
};
