import React, { createContext, useContext, useState, useCallback } from 'react';
import { ModalType, ModalPosition, ModalConfig } from '../core/types';

interface ModalContextType {
    modals: ModalConfig[];
    createModal: (params: { type: ModalType; position?: ModalPosition; content: unknown }) => Promise<ModalConfig>;
    removeModal: (id: string) => void;
    updateModalStyle: (id: string, style: { backgroundColor?: string }) => void;
}

const ModalContext = createContext<ModalContextType | undefined>(undefined);

export const ModalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [modals, setModals] = useState<ModalConfig[]>([]);

    const createModal = useCallback((params: { type: ModalType; position?: ModalPosition; content: unknown }) => {
        const newModal: ModalConfig = {
            id: Date.now().toString(),
            type: params.type,
            position: params.position || {
                x: 0,
                y: 0,
                width: '100%',
                height: '100%'
            },
            content: params.content
        };

        return new Promise<ModalConfig>((resolve) => {
            setModals(prev => {
                const newModals = [...prev, newModal];
                resolve(newModal);
                return newModals;
            });
        });
    }, []);

    const removeModal = useCallback((id: string) => {
        setModals(prev => prev.filter(modal => modal.id !== id));
    }, []);

    const updateModalStyle = useCallback((id: string, style: { backgroundColor?: string }) => {
        setModals(prev =>
            prev.map(modal =>
                modal.id === id ? { ...modal, style: { ...modal.style, ...style } } : modal
            )
        );
    }, []);

    return (
        <ModalContext.Provider value={{ modals, createModal, removeModal, updateModalStyle }}>
            {children}
        </ModalContext.Provider>
    );
};

export const useModal = () => {
    const context = useContext(ModalContext);
    if (context === undefined) {
        throw new Error('useModal must be used within a ModalProvider');
    }
    return context;
}; 