import { Difficulty, FillBlanksExercise, FillBlanksMCOption, ReadingPart } from "@/interfaces/exam";
import { useCallback, useEffect, useReducer, useState } from "react";
import BlanksEditor from "..";
import { Card, CardContent } from "@/components/ui/card";
import useExamEditorStore from "@/stores/examEditor";
import { blanksReducer, BlankState, getTextSegments } from "../BlanksReducer";
import useSectionEdit from "@/components/ExamEditor/Hooks/useSectionEdit";
import { AlertItem } from "../../Shared/Alert";
import validateBlanks from "../validateBlanks";
import { toast } from "react-toastify";
import setEditingAlert from "../../Shared/setEditingAlert";
import { MdEdit, MdEditOff } from "react-icons/md";
import MCOption from "./MCOption";
import { uuidv4 } from "@/utils/uuid";


const FillBlanksMC: React.FC<{ exercise: FillBlanksExercise; sectionId: number }> = ({ exercise, sectionId }) => {
    const { currentModule, dispatch } = useExamEditorStore();
    const difficulty = useExamEditorStore((state) => state.modules[currentModule].difficulty);
    const { state } = useExamEditorStore(
        (state) => state.modules[currentModule].sections.find((section) => section.sectionId === sectionId)!
    );

    const section = state as ReadingPart;
    const [alerts, setAlerts] = useState<AlertItem[]>([]);
    const [local, setLocal] = useState(exercise);
    const [selectedBlankId, setSelectedBlankId] = useState<string | null>(null);

    const [answers, setAnswers] = useState<Map<string, string>>(() => {
        return new Map(
            exercise.solutions.map(({ id, solution }) => [
                id.toString(),
                solution
            ])
        );
    });

    const [isEditMode, setIsEditMode] = useState(false);
    const [editing, setEditing] = useState(false);

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

    const [blanksState, blanksDispatcher] = useReducer(blanksReducer, {
        text: exercise.text || "",
        blanks: [],
        selectedBlankId: null,
        draggedItemId: null,
        textMode: false,
        setEditing,
    });

    const { handleSave, handleDiscard, handleDelete, handlePractice } = useSectionEdit({
        sectionId,
        editing,
        setEditing,
        onSave: () => {
            if (!validateBlanks(blanksState.blanks, answers, alerts, setAlerts)) {
                toast.error("Please fix the errors before saving!");
                return;
            }

            setEditing(false);
            setAlerts([]);

            const updatedExercise = {
                ...local,
                text: blanksState.text,
                solutions: Array.from(answers.entries()).map(([id, solution]) => ({
                    uuid: local.solutions.find(sol => sol.id === id)?.uuid || uuidv4(),
                    id,
                    solution
                }))
            };

            const newState = { ...section };
            newState.exercises = newState.exercises.map((ex) =>
                ex.id === exercise.id ? updatedExercise : ex
            );

            dispatch({ type: 'UPDATE_SECTION_STATE', payload: { sectionId, update: newState, module: currentModule } });
        },
        onDiscard: () => {
            setSelectedBlankId(null);
            setAnswers(new Map(exercise.solutions.map(({ id, solution }) => [id, solution])));
            setIsEditMode(false);
            setLocal(exercise);

            blanksDispatcher({ type: "RESET", payload: { text: exercise.text } });
            blanksDispatcher({ type: "SET_TEXT", payload: exercise.text || "" });

            const tokens = getTextSegments(exercise.text || "");
            const initialBlanks = tokens.reduce((acc, token, idx) => {
                if (token.type === 'blank') {
                    acc.push({ id: token.id, position: idx });
                }
                return acc;
            }, [] as BlankState[]);
            blanksDispatcher({ type: "SET_BLANKS", payload: initialBlanks });
        },
        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 } });
        }
    });

    useEffect(() => {
        if (!editing) {
            setLocal(exercise);
            setAnswers(new Map(exercise.solutions.map(({ id, solution }) => [id, solution])));
        }
    }, [exercise, editing]);

    const handleOptionSelect = (option: string) => {
        if (!selectedBlankId) return;
        if (!editing) setEditing(true);

        const newAnswers = new Map(answers);
        newAnswers.set(selectedBlankId, option);

        setAnswers(newAnswers);

        setLocal(prev => ({
            ...prev,
            solutions: Array.from(newAnswers.entries()).map(([id, solution]) => ({
                uuid: prev.solutions.find(sol => sol.id === id)?.uuid || uuidv4(),
                id,
                solution
            }))
        }));
    };

    const handleEditOption = (mcOptionIndex: number, key: keyof FillBlanksMCOption['options'], value: string) => {
        if (!editing) setEditing(true);

        setLocal(prev => {
            const newWords = [...prev.words] as FillBlanksMCOption[];
            const mcOption = newWords[mcOptionIndex] as FillBlanksMCOption;

            const newOptions = { ...mcOption.options, [key]: value };
            newWords[mcOptionIndex] = { ...mcOption, options: newOptions };

            const oldValue = (mcOption.options as any)[key];
            const newAnswers = new Map(answers);
            for (const [blankId, answer] of newAnswers.entries()) {
                if (answer === oldValue) {
                    newAnswers.set(blankId, value);
                }
            }
            setAnswers(newAnswers);

            return {
                ...prev,
                words: newWords,
                solutions: Array.from(newAnswers.entries()).map(([id, solution]) => ({
                    uuid: prev.solutions.find(sol => sol.id === id)?.uuid || uuidv4(),
                    id,
                    solution
                }))
            };
        });
    };

    useEffect(() => {
        validateBlanks(blanksState.blanks, answers, alerts, setAlerts);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [answers, blanksState.blanks, blanksState.textMode]);

    useEffect(() => {
        setEditingAlert(editing, setAlerts);
    }, [editing]);

    useEffect(() => {
        if (!editing) {
            setLocal(exercise);
            setAnswers(new Map(
                exercise.solutions.map(({ id, solution }) => [
                    id.toString(),
                    solution
                ])
            ));
        }
    }, [exercise, editing]);

    useEffect(() => {
        setAnswers(new Map(
            exercise.solutions.map(({ id, solution }) => [
                id.toString(),
                solution
            ])
        ));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const handleBlankRemove = (blankId: number) => {
        if (!editing) setEditing(true);

        const newAnswers = new Map(answers);
        newAnswers.delete(blankId.toString());
        setAnswers(newAnswers);

        setLocal(prev => ({
            ...prev,
            words: (prev.words as FillBlanksMCOption[]).filter(w => w.id !== blankId.toString()),
            solutions: Array.from(newAnswers.entries()).map(([id, solution]) => ({
                uuid: prev.solutions.find(sol => sol.id === id)?.uuid || uuidv4(),
                id,
                solution
            }))
        }));

        blanksDispatcher({ type: "REMOVE_BLANK", payload: blankId });
    };

    useEffect(() => {
        const existingWordIds = new Set((local.words as FillBlanksMCOption[]).map(word => word.id));
        const blanksMissingWords = blanksState.blanks.filter(blank => !existingWordIds.has(blank.id.toString()));
        if (blanksMissingWords.length > 0) {
            setLocal(prev => {
                const newWords = [...prev.words] as FillBlanksMCOption[];

                blanksMissingWords.forEach(blank => {
                    const newMCOption: FillBlanksMCOption = {
                        uuid: uuidv4(),
                        id: blank.id.toString(),
                        options: {
                            A: 'Option A',
                            B: 'Option B',
                            C: 'Option C',
                            D: 'Option D'
                        }
                    };
                    newWords.push(newMCOption);
                });

                return {
                    ...prev,
                    words: newWords,
                    solutions: Array.from(answers.entries()).map(([id, solution]) => ({
                        uuid: prev.solutions.find(sol => sol.id === id)?.uuid || uuidv4(),
                        id,
                        solution
                    }))
                };
            });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [blanksState.blanks]);

    const saveDifficulty = useCallback((diff: Difficulty) => {
        if (!difficulty.includes(diff)) {
            dispatch({ type: 'UPDATE_MODULE', payload: { updates: { difficulty: [...difficulty, diff]} } });
        }
        const updatedExercise = { ...exercise, difficulty: diff };
        const newState = { ...section };
        newState.exercises = newState.exercises.map((ex) => ex.id === exercise.id ? updatedExercise : ex );
        dispatch({ type: 'UPDATE_SECTION_STATE', payload: { sectionId, update: newState, module: currentModule } });
    }, [currentModule, difficulty, dispatch, exercise, section, sectionId]);

    return (
        <div className="space-y-4">
            <BlanksEditor
                alerts={alerts}
                editing={editing}
                state={blanksState}
                difficulty={exercise.difficulty}
                saveDifficulty={saveDifficulty}
                blanksDispatcher={blanksDispatcher}
                description="Place blanks and select the correct answer from multiple choice options"
                initialText={local.text}
                module={currentModule}
                showBlankBank={true}
                onBlankSelect={(blankId) => setSelectedBlankId(blankId?.toString() || null)}
                onSave={handleSave}
                onDiscard={handleDiscard}
                onDelete={handleDelete}
                onPractice={handlePractice}
                setEditing={setEditing}
                onBlankRemove={handleBlankRemove}
                isEvaluationEnabled={!local.isPractice}
                prompt={local.prompt}
                updatePrompt={(prompt: string) => updateLocal({ ...local, prompt })}
            >
                {!blanksState.textMode && selectedBlankId && (
                    <Card className="p-4">
                        <CardContent>
                            <div className="flex justify-between items-center mb-4">
                                <div className="text-lg font-semibold">Multiple Choice Options</div>
                                <button
                                    onClick={() => setIsEditMode(!isEditMode)}
                                    className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                >
                                    {isEditMode ?
                                        <MdEditOff size={20} className="text-gray-500" /> :
                                        <MdEdit size={20} className="text-gray-500" />
                                    }
                                </button>
                            </div>

                            {(local.words as FillBlanksMCOption[]).map((mcOption) => {
                                if (mcOption.id.toString() !== selectedBlankId) return null;

                                return (
                                    <MCOption
                                        key={mcOption.id}
                                        id={mcOption.id}
                                        options={mcOption.options}
                                        selectedOption={answers.get(selectedBlankId)}
                                        onSelect={(option) => handleOptionSelect(option)}
                                        isEditMode={isEditMode}
                                        onEdit={(key, value) => handleEditOption(
                                            (local.words as FillBlanksMCOption[]).findIndex(w => w.id === mcOption.id),
                                            key as "A" | "B" | "C" | "D",
                                            value
                                        )}
                                    />
                                );
                            })}
                        </CardContent>
                    </Card>
                )}
            </BlanksEditor>
        </div>
    );
};

export default FillBlanksMC;