import React, { useCallback, useState } from "react";
import SettingsEditor from ".";
import Option from "@/interfaces/option";
import Dropdown from "./Shared/SettingsDropdown";
import Input from "@/components/Low/Input";
import ExercisePicker from "../Shared/ExercisePicker";
import { generate } from "./Shared/Generate";
import GenerateBtn from "./Shared/GenerateBtn";
import useSettingsState from "../Hooks/useSettingsState";
import { ReadingPart } from "@/interfaces/exam";
import { ReadingSectionSettings } from "@/stores/examEditor/types";
import useExamEditorStore from "@/stores/examEditor";
import openDetachedTab from "@/utils/popout";
import { useRouter } from "next/router";
import { usePersistentExamStore } from "@/stores/examStore";

const ReadingSettings: React.FC = () => {
    const router = useRouter();

    const { currentModule } = useExamEditorStore();
    const {
        focusedSection,
        difficulty,
        sections,
    } = useExamEditorStore(state => state.modules[currentModule]);

    const { localSettings, updateLocalAndScheduleGlobal } = useSettingsState<ReadingSectionSettings>(
        currentModule,
        focusedSection
    );

    const currentSection = sections.find((section) => section.sectionId == focusedSection)!.state as ReadingPart;

    const defaultPresets: Option[] = [
        {
            label: "Preset: Writing Task 1",
            value: "Welcome to {part} of the {label}. You will write a letter of at least 150 words in response to a given situation. Your letter may be personal, semi-formal, or formal. You have 20 minutes for this task."
        },
        {
            label: "Preset: Writing Task 2",
            value: "Welcome to {part} of the {label}. You will write a semi-formal/neutral essay of at least 250 words on a topic of general interest. Discuss the given opinion, argument, or problem. Organize your ideas clearly and support them with relevant examples. You have 40 minutes for this task."
        }
    ];


    const generatePassage = useCallback(() => {
        generate(
            focusedSection,
            currentModule,
            "context",
            {
                method: 'GET',
                queryParams: {
                    difficulty,
                    ...(localSettings.topic && { topic: localSettings.topic })
                }
            },
            (data: any) => [{
                title: data.title,
                text: data.text
            }]
        );
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [localSettings.topic, difficulty, focusedSection]);

    const onTopicChange = useCallback((topic: string) => {
        updateLocalAndScheduleGlobal({ topic });
    }, [updateLocalAndScheduleGlobal]);


    const canPreview = sections.some(
        (s) => (s.state as ReadingPart).exercises && (s.state as ReadingPart).exercises.length > 0
    );

    return (
        <SettingsEditor
            sectionLabel={`Passage ${focusedSection}`}
            sectionId={focusedSection}
            module="reading"
            introPresets={[defaultPresets[focusedSection - 1]]}
            preview={() => { }}
            canPreview={canPreview}
        >
            <Dropdown
                title="Generate Passage"
                module={currentModule}
                open={localSettings.isPassageOpen}
                setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isPassageOpen: isOpen })}
            >
                <div className="flex flex-row gap-2 items-center px-2 pb-4">
                    <div className="flex flex-col flex-grow gap-4 px-2">
                        <label className="font-normal text-base text-mti-gray-dim">Topic (Optional)</label>
                        <Input
                            key={`section-${focusedSection}`}
                            type="text"
                            placeholder="Topic"
                            name="category"
                            onChange={onTopicChange}
                            roundness="full"
                            value={localSettings.topic}
                        />
                    </div>
                    <div className="flex self-end h-16 mb-1">
                        <GenerateBtn
                            module={currentModule}
                            genType="context"
                            sectionId={focusedSection}
                            generateFnc={generatePassage}
                        />
                    </div>
                </div>
            </Dropdown>
            <Dropdown
                title="Add Exercises"
                module={currentModule}
                open={localSettings.isExerciseDropdownOpen}
                setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isExerciseDropdownOpen: isOpen })}
                disabled={currentSection.text.content === "" || currentSection.text.title === ""}
            >
                <ExercisePicker
                    module="reading"
                    sectionId={focusedSection}
                    difficulty={difficulty}
                    extraArgs={{ text: currentSection.text.content }}
                />
            </Dropdown>
        </SettingsEditor>
    );
};

export default ReadingSettings;
