import { Module } from "@/interfaces";
import useExamEditorStore from "@/stores/examEditor";
import { Generating } from "@/stores/examEditor/types";
import clsx from "clsx";
import { useEffect, useState } from "react";
import { BsArrowRepeat } from "react-icons/bs";
import { GiBrain } from "react-icons/gi";

interface Props {
    module: Module;
    sectionId: number;
    genType: Generating;
    generateFnc: (sectionId: number) => void
    className?: string;
    level?: boolean;
    disabled?: boolean;
}

const GenerateBtn: React.FC<Props> = ({ module, sectionId, genType, generateFnc, className, level = false, disabled = false }) => {
    const section = useExamEditorStore((store) => store.modules[level ? "level" : module].sections.find((s) => s.sectionId == sectionId));
    const [loading, setLoading] = useState(false);

    const generating = section?.generating;
    const genResult = section?.genResult;
    const levelGenerating = section?.levelGenerating;
    const levelGenResults = section?.levelGenResults;

    useEffect(() => {
        const gen = level ? levelGenerating?.find(g => g === genType) !== undefined : (generating !== undefined && generating === genType);
        if (loading !== gen) {
            setLoading(gen);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [generating, levelGenerating, levelGenResults, genResult])

    if (section === undefined) return <></>;

    return (
        <button
            key={`section-${sectionId}`}
            className={clsx(
                "flex items-center w-[140px] justify-center px-4 py-2 text-white rounded-xl transition-colors duration-300 text-lg disabled:cursor-not-allowed",
                `bg-ielts-${module}/70 border border-ielts-${module} hover:bg-ielts-${module} disabled:bg-ielts-${module}/40`,
                className
            )}
            disabled={loading || disabled}
            onClick={(loading || disabled) ? () => { } : () => generateFnc(sectionId)}
        >
            {loading ? (
                <div key={`section-${sectionId}`} className="flex items-center justify-center">
                    <BsArrowRepeat className="text-white animate-spin" size={25} />
                </div>
            ) : (
                <div key={`section-${sectionId}`} className="flex flex-row">
                    <GiBrain className="mr-2" size={24} />
                    <span>Generate</span>
                </div>
            )}
        </button>
    );
}

export default GenerateBtn;
