import create from 'zustand';
import { ModalState, ModalAction, ModalConfig, ModalId } from '../core/types';
import { nanoid } from 'nanoid';

const initialState: ModalState = {
    modals: {},
    activeModal: null
};

export const useModalStore = create<ModalState & {
    dispatch: (action: ModalAction) => void;
}>((set) => ({
    ...initialState,
    dispatch: (action) => {
        set((state) => {
            switch (action.type) {
                case 'CREATE_MODAL':
                    const id = nanoid();
                    return {
                        ...state,
                        modals: {
                            ...state.modals,
                            [id]: {
                                ...action.payload,
                                id
                            }
                        }
                    };

                case 'UPDATE_MODAL':
                    return {
                        ...state,
                        modals: {
                            ...state.modals,
                            [action.payload.id]: {
                                ...state.modals[action.payload.id],
                                ...action.payload
                            }
                        }
                    };

                case 'DELETE_MODAL':
                    const { [action.payload.id]: _, ...remainingModals } = state.modals;
                    return {
                        ...state,
                        modals: remainingModals,
                        activeModal: state.activeModal === action.payload.id ? null : state.activeModal
                    };

                case 'UPDATE_POSITION':
                    return {
                        ...state,
                        modals: {
                            ...state.modals,
                            [action.payload.id]: {
                                ...state.modals[action.payload.id],
                                position: {
                                    ...state.modals[action.payload.id].position,
                                    ...action.payload.position
                                }
                            }
                        }
                    };

                case 'UPDATE_STYLE':
                    return {
                        ...state,
                        modals: {
                            ...state.modals,
                            [action.payload.id]: {
                                ...state.modals[action.payload.id],
                                style: {
                                    ...state.modals[action.payload.id].style,
                                    ...action.payload.style
                                }
                            }
                        }
                    };

                default:
                    return state;
            }
        });
    }
})); 