import useExamStore, { usePersistentExamStore } from "@/stores/exam";
import { useCallback, useEffect, useRef, useState } from "react";

export interface Answer {
    prompt: string;
    blob: string;
    questionIndex: number;
}

const useAnswers = (id: string, type: string, isPractice: boolean, prompts: any[], registerSolution: Function, preview: boolean) => {
    const [answers, setAnswers] = useState<Answer[]>([]);

    const examState = useExamStore((state) => state);
	const persistentExamState = usePersistentExamStore((state) => state);

    const { questionIndex } = !preview ? examState : persistentExamState;
    
    const currentBlobUrlRef = useRef<string | null>(null);

    const cleanupBlobUrl = useCallback((url: string) => {
        if (url.startsWith('blob:')) {
            URL.revokeObjectURL(url);
        }
    }, []);

    // Update answers with new recording
    const updateAnswers = useCallback((blobUrl: string) => {
        if (!blobUrl) return;

        setAnswers(prev => {
            // Cleanup old blob URL for this question if it exists
            const existingAnswer = prev.find(x => x.questionIndex === questionIndex);
            if (existingAnswer?.blob) {
                cleanupBlobUrl(existingAnswer.blob);
            }

            const filteredAnswers = prev.filter(x => x.questionIndex !== questionIndex);
            return [...filteredAnswers, {
                questionIndex,
                prompt: prompts[questionIndex].text,
                blob: blobUrl,
            }];
        });

        // Store current blob URL for cleanup
        currentBlobUrlRef.current = blobUrl;
    }, [questionIndex, prompts, cleanupBlobUrl]);

    // Register solutions
    useEffect(() => {
        registerSolution(() => ({
            exercise: id,
            solutions: answers,
            score: { correct: 100, total: 100, missing: 0 },
            type,
            isPractice
        }));
    }, [answers, id, type, isPractice, registerSolution]);

    return {
        answers,
        setAnswers,
        updateAnswers,
        getCurrentBlob: () => currentBlobUrlRef.current
    };
};

export default useAnswers;
