import Header from "@/components/ExamEditor/Shared/Header";
import QuestionsList from "../../Shared/QuestionsList";
import SortableQuestion from "../../Shared/SortableQuestion";
import UnderlineQuestion from "./UnderlineQuestion";
import useSectionEdit from "@/components/ExamEditor/Hooks/useSectionEdit";
import { toast } from "react-toastify";
import setEditingAlert from "../../Shared/setEditingAlert";
import { LevelPart, ListeningPart, MultipleChoiceExercise, MultipleChoiceQuestion, ReadingPart } from "@/interfaces/exam";
import useExamEditorStore from "@/stores/examEditor";
import { useEffect, useState } from "react";
import { MdAdd } from "react-icons/md";
import Alert, { AlertItem } from "../../Shared/Alert";
import PromptEdit from "../../Shared/PromptEdit";


const UnderlineMultipleChoice: React.FC<{exercise: MultipleChoiceExercise, sectionId: number}> = ({
    exercise,
    sectionId,
}) => {
    const { currentModule, dispatch } = useExamEditorStore();
    const { state } = useExamEditorStore(
        (state) => state.modules[currentModule].sections.find((section) => section.sectionId === sectionId)!
    );
    const section = state as ReadingPart | ListeningPart | LevelPart;
    
    const [local, setLocal] = useState(exercise);
    const [alerts, setAlerts] = useState<AlertItem[]>([]);

    useEffect(() => {
        setLocal(exercise);
    }, [exercise]);

    const updateLocal = (exercise: MultipleChoiceExercise) => {
        setLocal(exercise);
        setEditingAlert(true, setAlerts);
        setEditing(true);
    };

    const handleQuestionChange = (questionIndex: number, updatedQuestion: MultipleChoiceQuestion) => {
        const newQuestions = [...local.questions];
        newQuestions[questionIndex] = updatedQuestion;
        updateLocal({ ...local, questions: newQuestions });
    };

    const addQuestion = () => {
        const newId = (parseInt(local.questions[local.questions.length - 1].id) + 1).toString();
        const options = Array.from({ length: 4 }, (_, i) => ({
            id: String.fromCharCode(65 + i),
            text: ''
        }));

        updateLocal({
            ...local,
            questions: [
                ...local.questions,
                {
                    prompt: "",
                    solution: "",
                    id: newId,
                    options,
                    variant: "text"
                },
            ]
        });
    };

    const deleteQuestion = (index: number) => {
        if (local.questions.length === 1) {
            toast.error("There needs to be at least one question!");
            return;
        }

        const newQuestions = local.questions.filter((_, i) => i !== index);
        updateLocal({ ...local, questions: newQuestions });
    };

    const { editing, handleSave, handleDiscard, handleDelete, handlePractice, setEditing } = useSectionEdit({
        sectionId,
        onSave: () => {
            setEditing(false);
            setAlerts([]);
            const newSection = {
                ...section,
                exercises: section.exercises.map((ex) => 
                    ex.id === local.id ? local : ex
                )
            };
            dispatch({ type: "UPDATE_SECTION_STATE", payload: { sectionId, update: newSection, module: currentModule } });
        },
        onDiscard: () => {
            setAlerts([]);
            setLocal(exercise);
            setEditing(false);
        },
        onDelete: () => {
            const newSection = {
                ...section,
                exercises: section.exercises.filter((ex) => ex.id !== local.id)
            };
            dispatch({ type: "UPDATE_SECTION_STATE", payload: { sectionId, update: newSection, module: currentModule } });
        },
        onPractice: () => {
            const updatedExercise = {
                ...local,
                isPractice: !local.isPractice
            };
            const newState = { ...section };
            newState.exercises = newState.exercises.map((ex) =>
                ex.id === exercise.id ? updatedExercise : ex
            );
            setLocal((prev) => ({...prev, isPractice: !local.isPractice}))
            dispatch({ type: 'UPDATE_SECTION_STATE', payload: { sectionId, update: newState, module: currentModule } });
        }
    });

    return (
        <div className="p-4">
            <Header
                title='Underline Multiple Choice Exercise'
                description="Edit questions with 4 underline options each"
                editing={editing}
                handleSave={handleSave}
                handleDelete={handleDelete}
                handlePractice={handlePractice}
                handleDiscard={handleDiscard}
                isEvaluationEnabled={!local.isPractice}
            />
            {alerts.length > 0 && <Alert className="mb-6" alerts={alerts} />}
            <PromptEdit value={local.prompt} onChange={(prompt: string) => updateLocal({...local, prompt})} />
            <div className="space-y-4">
                <QuestionsList
                    ids={local.questions.map(q => q.id)}
                    handleDragEnd={()=> {}}
                >
                    {local.questions.map((question, questionIndex) => (
                        <SortableQuestion
                            key={question.id}
                            id={question.id}
                            index={questionIndex}
                            deleteQuestion={() => deleteQuestion(questionIndex)}
                        >
                            <UnderlineQuestion
                                question={question}
                                onQuestionChange={(updatedQuestion) => 
                                    handleQuestionChange(questionIndex, updatedQuestion)
                                }
                            />
                        </SortableQuestion>
                    ))}
                </QuestionsList>

                <button
                    onClick={addQuestion}
                    className="w-full p-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors flex items-center justify-center gap-2 text-gray-600 hover:text-blue-600"
                >
                    <MdAdd size={18} />
                    Add New Question
                </button>
            </div>
        </div>
    );
};

export default UnderlineMultipleChoice;