import React, { useCallback, useEffect, useState } from "react";
import SettingsEditor from "..";
import Option from "@/interfaces/option";
import useSettingsState from "../../Hooks/useSettingsState";
import { WritingSectionSettings } from "@/stores/examEditor/types";
import useExamEditorStore from "@/stores/examEditor";
import { useRouter } from "next/router";
import { usePersistentExamStore } from "@/stores/exam";
import openDetachedTab from "@/utils/popout";
import { WritingExam, WritingExercise } from "@/interfaces/exam";
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,
        type,
        academic_url
    } = 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, index) => {
                const exercise = s.state as WritingExercise;
                if (type === "academic" && index == 0 && academic_url) {
                    exercise["attachment"] = {
                        url: academic_url,
                        description: "Visual Information"
                    }
                }

                return {
                    ...exercise,
                    intro: s.settings.currentIntro,
                    category: s.settings.category
                };
            }),
            minTimer,
            module: "writing",
            id: title,
            isDiagnostic: false,
            variant: undefined,
            difficulty,
            private: isPrivate,
            type: type!
        });
        setExerciseIndex(0);
        openDetachedTab("popout?type=Exam&module=writing", router)
    }

    const submitWriting = async () => {
        if (title === "") {
            toast.error("Enter a title for the exam!");
            return;
        }
        try {
            let firebase_url: string | undefined = undefined;
            if (type === "academic" && academic_url) {
                const formData = new FormData();
                const fetchedBlob = await fetch(academic_url);
                const blob = await fetchedBlob.blob();
                formData.append('file', blob);

                const response = await axios.post('/api/storage', formData, {
                    params: {
                        directory: 'writing_attachments'
                    },
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                firebase_url = response.data.urls[0];
            }

            const exam: WritingExam = {
                exercises: sections.map((s, index) => {
                    const exercise = s.state as WritingExercise;
                    if (index == 0 && firebase_url) {
                        exercise["attachment"] = {
                            url: firebase_url,
                            description: "Visual Information"
                        }
                    }

                    return {
                        ...exercise,
                        intro: localSettings.currentIntro,
                        category: localSettings.category
                    };
                }),
                minTimer,
                module: "writing",
                id: title,
                isDiagnostic: false,
                variant: undefined,
                difficulty,
                private: isPrivate,
                type: type!
            };

            const result = await axios.post(`/api/exam/writing`, exam)
            playSound("sent");
            toast.success(`Submitted Exam ID: ${result.data.id}`);

        } catch (error: any) {
            console.error('Error submitting exam:', error);
            toast.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;
