import { useEffect, useState } from "react";
import { LevelPart, ReadingPart } from "@/interfaces/exam";
import Input from "@/components/Low/Input";
import AutoExpandingTextArea from "@/components/Low/AutoExpandingTextarea";
import Passage from "../../Shared/Passage";
import SectionContext from ".";
import useExamEditorStore from "@/stores/examEditor";
import useSectionEdit from "../../Hooks/useSectionEdit";
import { Module } from "@/interfaces";

interface Props {
    module: Module;
    sectionId: number;
}


const ReadingContext: React.FC<Props> = ({ sectionId, module }) => {
    const { dispatch } = useExamEditorStore();
    const sectionState = useExamEditorStore(
        (state) => state.modules[module].sections.find((section) => section.sectionId === sectionId)!
    );

    const { genResult, state, levelGenResults, levelGenerating } = sectionState;
    const readingPart = state as ReadingPart | LevelPart;

    const [title, setTitle] = useState(readingPart.text?.title || '');
    const [content, setContent] = useState(readingPart.text?.content || '');
    const [passageOpen, setPassageOpen] = useState(false);

    const { editing, handleSave, handleDiscard, handleEdit, setEditing } = useSectionEdit({
        sectionId,
        onSave: () => {
            let newState = { ...state } as ReadingPart | LevelPart;
            newState.text = {
                title, content
            }
            dispatch({ type: 'UPDATE_SECTION_STATE', payload: { sectionId, update: newState, module } })
            setEditing(false);

            if (genResult) {
                dispatch({ type: "UPDATE_SECTION_SINGLE_FIELD", payload: { sectionId, module, field: "genResult", value: undefined } })
            }

            if (levelGenResults.find((res) => res.generating === "passage")) {
                dispatch({ type: "UPDATE_SECTION_SINGLE_FIELD", payload: { sectionId, module, field: "levelGenResults", value: levelGenResults.filter((res) => res.generating !== "passage") } })
            }
        },
        onDiscard: () => {
            setTitle(readingPart.text?.title || '');
            setContent(readingPart.text?.content || '');
        },
        onEdit: () => {
            setPassageOpen(false);
        }
    });

    useEffect(() => {
        if (readingPart.text === undefined) {
            setTitle('');
            setContent('');
        }
    }, [readingPart])

    useEffect(() => {
        if (genResult && genResult.generating === "passage") {
            setEditing(true);
            setTitle(genResult.result[0].title);
            setContent(genResult.result[0].text);
            dispatch({ type: "UPDATE_SECTION_SINGLE_FIELD", payload: { sectionId, module, field: "generating", value: undefined } })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [genResult]);


    useEffect(() => {
        const passageRes = [...levelGenResults].reverse()
        .find((res) => res.generating === "passage");

        if (levelGenResults && passageRes) {
            setEditing(true);
            setTitle(passageRes.result[0].title);
            setContent(passageRes.result[0].text);
            dispatch({ type: "UPDATE_SECTION_SINGLE_FIELD", payload: { sectionId, module, field: "levelGenerating", value: levelGenerating.filter(g => g !== "passage") } })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [levelGenResults]);


    const renderContent = (editing: boolean) => {
        if (editing) {
            return (
                <div className="flex flex-col text-mti-gray-dim p-4 gap-4">
                    <Input
                        type="text"
                        placeholder="Insert a title here"
                        name="title"
                        label="Title"
                        onChange={setTitle}
                        roundness="xl"
                        defaultValue={title}
                        required
                    />
                    <div className="flex flex-col gap-3">
                        <label className="font-normal text-base text-mti-gray-dim">Content *</label>
                        <AutoExpandingTextArea
                            value={content}
                            placeholder="Insert a passage here"
                            onChange={(text) => setContent(text)}
                        />
                    </div>
                </div>
            );
        }

        return content === "" || title === "" ? (
            <p className="w-full text-gray-600 px-7 py-8 border-2 bg-white rounded-3xl whitespace-pre-line">
                Generate or edit the passage to add exercises!
            </p>
        ) : (
            <Passage
                title={title}
                content={content}
                open={passageOpen}
                setIsOpen={setPassageOpen}
            />
        );
    };

    return (
        <SectionContext
            sectionId={sectionId}
            title="Reading Passage"
            description="The reading passage that the exercises will refer to."
            renderContent={renderContent}
            editing={editing}
            onSave={handleSave}
            onEdit={handleEdit}
            module={module}
            onDiscard={handleDiscard}
            context="passage"
        />
    );
};

export default ReadingContext;
