import { useCallback, useEffect, useState } from "react";
import useExamEditorStore from "@/stores/examEditor";
import ExamEditorStore, { Generating } from "@/stores/examEditor/types";
import Header from "../../Shared/Header";
import { Module } from "@/interfaces";
import GenLoader from "../../Exercises/Shared/GenLoader";

interface Props {
    sectionId: number;
    title: string;
    description: string;
    editing: boolean;
    renderContent: (editing: boolean, listeningSection?: number) => React.ReactNode;
    mode?: "edit" | "delete";
    onSave: () => void;
    onDiscard: () => void;
    onEdit?: () => void;
    module: Module;
    listeningSection?: number;
    context: Generating;
}

const SectionContext: React.FC<Props> = ({ sectionId, title, description, renderContent, editing, onSave, onDiscard, onEdit, mode = "edit", module, context, listeningSection }) => {
    const { currentModule } = useExamEditorStore();
    const { generating, levelGenerating } = useExamEditorStore(
        (state) => state.modules[currentModule].sections.find((section) => section.sectionId === sectionId)!
    );

    const [loading, setLoading] = useState(generating && generating === context);

    useEffect(() => {
        const gen = module === "level" ? levelGenerating.find(g => g === context) !== undefined : generating && generating === context;
        if (loading !== gen) {
            setLoading(gen);
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [generating, levelGenerating]);

    return (
        <div className="p-8 shadow-inner border border-gray-200 bg-gray-50 rounded-xl">
            <div className='relative pb-4'>
                <Header
                    title={title}
                    description={description}
                    editing={editing}
                    handleSave={onSave}
                    handleDiscard={onDiscard}
                    handleEdit={onEdit}
                    module={module}
                />
            </div>
            <div className="mt-4">
                {loading ? (
                    <GenLoader module={module} />
                ) : (
                    renderContent(editing, listeningSection)
                )}
            </div>
        </div>
    );
};

export default SectionContext;
