import { useCallback, useEffect, useState } from 'react';
import { InteractiveSpeakingExercise, LevelPart, SpeakingExercise } from "@/interfaces/exam";
import { Section } from '@/stores/examEditor/types';

interface CheckGenerateProps {
    section: Section | null;
    sections: Array<{ sectionId: number; state: Section }>;
    id?: string;
    focusedSection: number;
}

const useCanGenerate = ({ section, sections, id, focusedSection }: CheckGenerateProps) => {
    const checkCanGenerate = useCallback(() => {
        if (!section) return false;


        const exercise = id
            ? (sections.find(s => s.sectionId === 1)?.state as LevelPart)
                ?.exercises?.find(ex => ex.id === id) ?? section
            : section;

        const sectionId = id ? (exercise as SpeakingExercise | InteractiveSpeakingExercise).sectionId : focusedSection;

        switch (sectionId) {
            case 1: {
                const currentSection = exercise as InteractiveSpeakingExercise;
                return currentSection.first_title &&
                    currentSection.second_title &&
                    currentSection.prompts?.length > 2 &&
                    currentSection.prompts.every(prompt => prompt.text)
                    ;
            }
            case 2: {
                const currentSection = exercise as SpeakingExercise;
                return currentSection.title &&
                    currentSection.text &&
                    currentSection.prompts?.length > 0 &&
                    currentSection.prompts.every(prompt => prompt)
                    ;
            }
            case 3: {
                const currentSection = exercise as InteractiveSpeakingExercise;
                return currentSection.title &&
                    currentSection.prompts?.length > 0 &&
                    currentSection.prompts.every(prompt => prompt.text)
                    ;
            }
            default:
                return false;
        }
    }, [section, sections, id, focusedSection]);

    const [canGenerate, setCanGenerate] = useState(checkCanGenerate());

    useEffect(() => {
        setCanGenerate(checkCanGenerate());
    }, [checkCanGenerate, section]);

    return canGenerate;
};

export default useCanGenerate;
