import useExamEditorStore from "@/stores/examEditor";
import useSettingsState from "../Hooks/useSettingsState";
import { SpeakingSectionSettings } from "@/stores/examEditor/types";
import Option from "@/interfaces/option";
import { useCallback } from "react";
import { generate } from "./Shared/Generate";
import SettingsEditor from ".";
import Dropdown from "./Shared/SettingsDropdown";
import Input from "@/components/Low/Input";
import GenerateBtn from "./Shared/GenerateBtn";
import clsx from "clsx";


const SpeakingSettings: React.FC = () => {

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

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

    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 generateScript = useCallback((sectionId: number) => {
        const queryParams: {
            difficulty: string;
            first_topic?: string;
            second_topic?: string;
            topic?: string;
        } = { difficulty };
        
        if (sectionId === 1) {
            if (localSettings.topic) {
                queryParams['first_topic'] = localSettings.topic;
            }
            if (localSettings.secondTopic) {
                queryParams['second_topic'] = localSettings.secondTopic;
            }
        } else {
            if (localSettings.topic) {
                queryParams['topic'] = localSettings.topic;
            }
        }

        generate(
            sectionId,
            currentModule,
            "context", // <- not really context but exercises is reserved for reading, listening and level
            {
                method: 'GET',
                queryParams
            },
            (data: any) => {
                switch (sectionId) {
                    case 1:
                        return [{
                            prompts: data.questions,
                            first_topic: data.first_topic,
                            second_topic: data.second_topic
                        }];
                    case 2:
                        return [{
                            topic: data.topic,
                            question: data.question,
                            prompts: data.prompts,
                            suffix: data.suffix
                        }];
                    case 3:
                        return [{
                            title: data.topic,
                            prompts: data.questions
                        }];
                    default:
                        return [data];
                }
            }
        );
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [localSettings, difficulty]);

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

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

    return (
        <SettingsEditor
            sectionLabel={`Speaking ${focusedSection}`}
            sectionId={focusedSection}
            module="speaking"
            introPresets={[defaultPresets[focusedSection - 1]]}
            preview={() => { }}
            canPreview={false}
            canSubmit={false}
            submitModule={()=> {}}
        >
            <Dropdown
                title="Generate Script"
                module={currentModule}
                open={localSettings.isExerciseDropdownOpen}
                setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isExerciseDropdownOpen: isOpen }, false)}
            >

                <div className={clsx("gap-2 px-2 pb-4", focusedSection === 1 ? "flex flex-col w-full" : "flex flex-row items-center" )}>
                    <div className="flex flex-col flex-grow gap-4 px-2">
                        <label className="font-normal text-base text-mti-gray-dim">{`${focusedSection === 1 ? "First Topic" : "Topic"}`} (Optional)</label>
                        <Input
                            key={`section-${focusedSection}`}
                            type="text"
                            placeholder="Topic"
                            name="category"
                            onChange={onTopicChange}
                            roundness="full"
                            value={localSettings.topic}
                        />
                    </div>
                    {focusedSection === 1 &&
                        <div className="flex flex-col flex-grow gap-4 px-2">
                            <label className="font-normal text-base text-mti-gray-dim">Second Topic (Optional)</label>
                            <Input
                                key={`section-${focusedSection}`}
                                type="text"
                                placeholder="Topic"
                                name="category"
                                onChange={onSecondTopicChange}
                                roundness="full"
                                value={localSettings.secondTopic}
                            />
                        </div>
                    }
                    <div className={clsx("flex h-16 mb-1", focusedSection === 1 ? "justify-center mt-4" : "self-end")}>
                        <GenerateBtn
                            module={currentModule}
                            genType="context"
                            sectionId={focusedSection}
                            generateFnc={generateScript}
                        />
                    </div>
                </div>
            </Dropdown>
            <Dropdown
                title="Generate Video"
                module={currentModule}
                open={localSettings.isGenerateAudio}
                setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isGenerateAudio: isOpen }, false)}
            >
                <div className={clsx("gap-2 px-2 pb-4 flex flex-row items-center" )}>
                    
                    <div className={clsx("flex h-16 mb-1", focusedSection === 1 ? "justify-center mt-4" : "self-end")}>
                        <GenerateBtn
                            module={currentModule}
                            genType="media"
                            sectionId={focusedSection}
                            generateFnc={generateScript}
                        />
                    </div>
                </div>
            </Dropdown>
        </SettingsEditor>
    );
};

export default SpeakingSettings;
