import Dropdown from "../Shared/SettingsDropdown";
import ExercisePicker from "../../ExercisePicker";
import SettingsEditor from "..";
import GenerateBtn from "../Shared/GenerateBtn";
import { useCallback, useState } from "react";
import { generate } from "../Shared/Generate";
import { Generating, LevelSectionSettings, ListeningSectionSettings } from "@/stores/examEditor/types";
import Option from "@/interfaces/option";
import useExamEditorStore from "@/stores/examEditor";
import useSettingsState from "../../Hooks/useSettingsState";
import { ListeningExam, ListeningPart } from "@/interfaces/exam";
import Input from "@/components/Low/Input";
import openDetachedTab from "@/utils/popout";
import { useRouter } from "next/router";
import axios from "axios";
import { usePersistentExamStore } from "@/stores/exam";
import { playSound } from "@/utils/sound";
import { toast } from "react-toastify";
import ListeningComponents from "./components";

const ListeningSettings: React.FC = () => {
    const router = useRouter();
    const { currentModule, title } = useExamEditorStore();
    const {
        focusedSection,
        difficulty,
        sections,
        minTimer,
        isPrivate,
    } = useExamEditorStore(state => state.modules[currentModule]);

    const {
        setExam,
        setExerciseIndex,
        setPartIndex,
        setQuestionIndex,
        setBgColor,
    } = usePersistentExamStore();

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

    const currentSection = sections.find((section) => section.sectionId == focusedSection)?.state as ListeningPart;

    const defaultPresets: Option[] = [
        {
            label: "Preset: Listening Section 1",
            value: "Welcome to {part} of the {label}. You will hear a conversation between two people in an everyday social context. This may include topics such as making arrangements or bookings, inquiring about services, or handling basic transactions."
        },
        {
            label: "Preset: Listening Section 2",
            value: "Welcome to {part} of the {label}. You will hear a monologue set in an everyday social context. This may include a speech about local facilities, arrangements for social occasions, or general announcements."
        },
        {
            label: "Preset: Listening Section 3",
            value: "Welcome to {part} of the {label}. You will hear a conversation between up to four people in an educational or training context. This may include discussions about assignments, research projects, or course requirements."
        },
        {
            label: "Preset: Listening Section 4",
            value: "Welcome to {part} of the {label}. You will hear an academic lecture or talk on a specific subject."
        }
    ];

    const submitListening = async () => {
        if (title === "") {
            toast.error("Enter a title for the exam!");
            return;
        }
        try {
            const sectionsWithAudio = sections.filter(s => (s.state as ListeningPart).audio?.source);

            if (sectionsWithAudio.length > 0) {
                const formData = new FormData();
                const sectionMap = new Map<number, string>();

                await Promise.all(
                    sectionsWithAudio.map(async (section) => {
                        const listeningPart = section.state as ListeningPart;
                        const blobUrl = listeningPart.audio!.source;
                        const response = await fetch(blobUrl);
                        const blob = await response.blob();
                        formData.append('file', blob, 'audio.mp3');
                        sectionMap.set(section.sectionId, blobUrl);
                    })
                );

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

                const { urls } = response.data;

                const exam: ListeningExam = {
                    parts: sectionsWithAudio.map((s) => {
                        const part = s.state as ListeningPart;
                        const index = Array.from(sectionMap.entries())
                            .findIndex(([id]) => id === s.sectionId);

                        return {
                            ...part,
                            audio: part.audio ? {
                                ...part.audio,
                                source: index !== -1 ? urls[index] : part.audio.source
                            } : undefined,
                            intro: s.settings.currentIntro,
                            category: s.settings.category
                        };
                    }),
                    isDiagnostic: false,
                    minTimer,
                    module: "listening",
                    id: title,
                    variant: sections.length === 4 ? "full" : "partial",
                    difficulty,
                    private: isPrivate,
                };

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

            } else {
                toast.error('No audio sections found in the exam! Please either import them or generate them.');
            }

        } catch (error: any) {
            console.error('Error submitting exam:', error);
            toast.error(
                "Something went wrong while submitting, please try again later."
            );
        }
    };


    const preview = () => {
        setExam({
            parts: sections.map((s) => {
                const exercise = s.state as ListeningPart;
                return {
                    ...exercise,
                    intro: s.settings.currentIntro,
                    category: s.settings.category
                };
            }),
            minTimer,
            module: "listening",
            id: title,
            isDiagnostic: false,
            variant: sections.length === 4 ? "full" : "partial",
            difficulty,
            private: isPrivate,
        } as ListeningExam);
        setExerciseIndex(0);
        setQuestionIndex(0);
        setPartIndex(0);
        setBgColor("bg-white");
        openDetachedTab("popout?type=Exam&module=listening", router)
    }


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

    const canSubmit = sections.every(
        (s) => (s.state as ListeningPart).exercises &&
            (s.state as ListeningPart).exercises.length > 0 &&
            (s.state as ListeningPart).audio !== undefined
    );

    return (
        <SettingsEditor
            sectionLabel={`Section ${focusedSection}`}
            sectionId={focusedSection}
            module="listening"
            introPresets={[defaultPresets[focusedSection - 1]]}
            canPreview={canPreview}
            canSubmit={canSubmit}
            preview={preview}
            submitModule={submitListening}
        >
            <ListeningComponents
                {...{ localSettings, updateLocalAndScheduleGlobal, currentSection }}
            />
        </SettingsEditor>
    );
};

export default ListeningSettings;