import React, { useState } from 'react';
import QuizList from './Quiz/QuizList';
import QuizBuilder from './Quiz/QuizBuilder';
import QuizResults from './Quiz/QuizResults';

type View = 'list' | 'create' | 'edit' | 'results';

interface Quiz {
    id: number;
    quiz_name: string;
    description: string;
    initial_form_id: number | null;
    questions: any[];
    settings: any;
    created_at: string;
    updated_at: string;
}

const Quizzes: React.FC = () => {
    const [currentView, setCurrentView] = useState<View>('list');
    const [selectedQuiz, setSelectedQuiz] = useState<Quiz | null>(null);

    const handleCreateQuiz = () => {
        setSelectedQuiz(null);
        setCurrentView('create');
    };

    const handleEditQuiz = (quiz: Quiz) => {
        setSelectedQuiz(quiz);
        setCurrentView('edit');
    };

    const handleViewResults = (quiz: Quiz) => {
        setSelectedQuiz(quiz);
        setCurrentView('results');
    };

    const handleBackToList = () => {
        setSelectedQuiz(null);
        setCurrentView('list');
    };

    const handleSaveQuiz = () => {
        // Refresh list after save
        setCurrentView('list');
        setSelectedQuiz(null);
    };

    return (
        <div className="quizzes-container">
            {currentView === 'list' && (
                <QuizList
                    onCreateQuiz={handleCreateQuiz}
                    onEditQuiz={handleEditQuiz}
                    onViewResults={handleViewResults}
                />
            )}

            {(currentView === 'create' || currentView === 'edit') && (
                <QuizBuilder
                    quizId={selectedQuiz?.id}
                    onBack={handleBackToList}
                    onSave={handleSaveQuiz}
                />
            )}

            {currentView === 'results' && selectedQuiz && (
                <QuizResults
                    quizId={selectedQuiz.id}
                    quizName={selectedQuiz.quiz_name}
                    onBack={handleBackToList}
                />
            )}
        </div>
    );
};

export default Quizzes;
