import React, { useCallback, useEffect, useState } from "react";
import SettingsEditor from "..";
import Option from "@/interfaces/option";
import Dropdown from "../Shared/SettingsDropdown";
import Input from "@/components/Low/Input";
import { generate } from "../Shared/Generate";
import useSettingsState from "../../Hooks/useSettingsState";
import GenerateBtn from "../Shared/GenerateBtn";
import { WritingSectionSettings } from "@/stores/examEditor/types";
import useExamEditorStore from "@/stores/examEditor";
import { useRouter } from "next/router";
import { usePersistentExamStore } from "@/stores/examStore";
import openDetachedTab from "@/utils/popout";
import { WritingExam, WritingExercise } from "@/interfaces/exam";
import { v4 } from "uuid";
import axios from "axios";
import { playSound } from "@/utils/sound";
import { toast } from "react-toastify";
import WritingComponents from "./components";

const WritingSettings: React.FC = () => {
    const router = useRouter();
    const [canPreviewOrSubmit, setCanPreviewOrSubmit] = useState(false);

    const { currentModule, title } = useExamEditorStore();
    const {
        minTimer,
        difficulty,
        isPrivate,
        sections,
        focusedSection,
    } = useExamEditorStore((store) => store.modules["writing"]);

    const states = sections.flatMap((s) => s.state) as WritingExercise[];

    const {
        setExam,
        setExerciseIndex,
    } = usePersistentExamStore();

    const { localSettings, updateLocalAndScheduleGlobal } = useSettingsState<WritingSectionSettings>(
        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."
        }
    ];

    useEffect(() => {
        setCanPreviewOrSubmit(states.some((s) => s.prompt !== ""))
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [states.some((s) => s.prompt !== "")])

    const openTab = () => {
        setExam({
            exercises: sections.map((s) => {
                const exercise = s.state as WritingExercise;
                return {
                    ...exercise,
                    intro: s.settings.currentIntro,
                    category: s.settings.category
                };
            }),
            minTimer,
            module: "writing",
            id: title,
            isDiagnostic: false,
            variant: undefined,
            difficulty,
            private: isPrivate,
        });
        setExerciseIndex(0);
        openDetachedTab("popout?type=Exam&module=writing", router)
    }

    const submitWriting = () => {
        const exam: WritingExam = {
            exercises: sections.map((s) => {
                const exercise = s.state as WritingExercise;
                return {
                    ...exercise,
                    intro: localSettings.currentIntro,
                    category: localSettings.category
                };
            }),
            minTimer,
            module: "writing",
            id: title,
            isDiagnostic: false,
            variant: undefined,
            difficulty,
            private: isPrivate,
        };

        axios
            .post(`/api/exam/reading`, exam)
            .then((result) => {
                playSound("sent");
                toast.success(`Submitted Exam ID: ${result.data.id}`);
            })
            .catch((error) => {
                console.log(error);
                toast.error(error.response.data.error || "Something went wrong while submitting, please try again later.");
            })
    }

    return (
        <SettingsEditor
            sectionLabel={`Task ${focusedSection}`}
            sectionId={focusedSection}
            module="writing"
            introPresets={[defaultPresets[focusedSection - 1]]}
            preview={openTab}
            canPreview={canPreviewOrSubmit}
            canSubmit={canPreviewOrSubmit}
            submitModule={submitWriting}
        >
            <WritingComponents
                {...{ localSettings, updateLocalAndScheduleGlobal }}
            />
        </SettingsEditor>
    );
};

export default WritingSettings;
