import { useState, useEffect, useCallback } from 'react';
import configData from '../config.json'; // We'll move or import config relative to src

const defaultConfig = { maxNumber: 180 };

export function useLuckyDraw() {
    const [maxNumber, setMaxNumber] = useState(180);
    const [pool, setPool] = useState([]);
    const [history, setHistory] = useState([]);
    const [isSpinning, setIsSpinning] = useState(false);
    const [currentWinner, setCurrentWinner] = useState(null);
    const [isInitialized, setIsInitialized] = useState(false);
    const [showModal, setShowModal] = useState(false);

    const generatePool = (max) => Array.from({ length: max }, (_, i) => i + 1);

    // Initialize from localStorage or defaults
    useEffect(() => {
        const saved = localStorage.getItem('luckyDrawState');
        if (saved) {
            try {
                const parsed = JSON.parse(saved);
                const loadedMax = parsed.maxNumber || 180;
                setMaxNumber(loadedMax);

                // If pool exists and has items, use it. Otherwise generate a new one.
                if (parsed.remainingNumbers && parsed.remainingNumbers.length > 0) {
                    setPool(parsed.remainingNumbers);
                } else {
                    // Pool is empty or missing, generate new pool
                    setPool(generatePool(loadedMax));
                }

                setHistory(parsed.drawHistory || []);
            } catch (e) {
                console.error('Failed to parse saved state', e);
                setPool(generatePool(180));
            }
        } else {
            // No saved state, initialize fresh
            setPool(generatePool(180));
        }
        setIsInitialized(true);
    }, []);

    // Save on change (only after initialization to avoid saving empty state)
    useEffect(() => {
        if (!isInitialized) return;

        const stateToSave = {
            maxNumber,
            remainingNumbers: pool,
            drawHistory: history
        };
        localStorage.setItem('luckyDrawState', JSON.stringify(stateToSave));
    }, [pool, history, maxNumber, isInitialized]);

    const resetPool = (newMax = maxNumber) => {
        const p = generatePool(newMax);
        setPool(p);
        setHistory([]);
        setMaxNumber(newMax);
        setCurrentWinner(null);
    };

    const drawNumber = useCallback(() => {
        if (pool.length === 0 || isSpinning) return null;

        setIsSpinning(true);
        const randomIndex = Math.floor(Math.random() * pool.length);
        const winner = pool[randomIndex];

        // We don't remove immediately from state to allow animation to finish logically if we wanted,
        // but typically we determine winner now and update state.
        // Let's update pool AFTER animation to be safe? 
        // Or update now. Update now is fine, we just display animation.

        const newPool = [...pool];
        newPool.splice(randomIndex, 1);
        setPool(newPool);

        // We'll return the winner to the UI to trigger animation
        setCurrentWinner(winner);

        // Return a promise that resolves when animation "time" is visually done?
        // Or just return the winner.
        return winner;
    }, [pool, isSpinning]);

    const completeDraw = useCallback((winner) => {
        setHistory(prev => [winner, ...prev]);
        setShowModal(true);
        // Don't set isSpinning to false yet - wait for modal confirmation
    }, []);

    const confirmWinner = useCallback(() => {
        setShowModal(false);
        setCurrentWinner(null);  // Reset to 000
        setIsSpinning(false);    // Allow next draw
    }, []);

    return {
        maxNumber,
        setMaxNumber,
        pool,
        history,
        isSpinning,
        currentWinner,
        drawNumber,
        completeDraw,
        resetPool,
        showModal,
        confirmWinner
    };
}
