import { useEffect, useState } from "react";
import { 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";


const ReadingContext: React.FC<{sectionId: number;}> = ({sectionId}) => {
    const {currentModule, dispatch } = useExamEditorStore();
    const { genResult, state, generating } = useExamEditorStore(
        (state) => state.modules[currentModule].sections.find((section) => section.sectionId === sectionId)!
    );
    const readingPart = state as ReadingPart;

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

    const { editing, handleSave, handleDiscard, modeHandle, setEditing } = useSectionEdit({
        sectionId,
        mode: "edit",
        onSave: () => {
            let newState = {...state} as ReadingPart;
            newState.text.title = title;
            newState.text.content = content;
            dispatch({type: 'UPDATE_SECTION_STATE', payload: {sectionId, update: newState}})
            setEditing(false);
        },
        onDiscard: () => {
            setTitle(readingPart.text.title);
            setContent(readingPart.text.content);
        },
        onMode: () => {
            setPassageOpen(false);
        }
    });

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


    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={modeHandle}
            module={currentModule}
            onDiscard={handleDiscard}
        />
    );
};

export default ReadingContext;
