import { IStoreItem, MetadataType } from "@rpg-engine/shared";
import { useState } from "react";

interface IUseStoreMetadata {
    collectMetadata: (item: IStoreItem) => Promise<Record<string, any> | null>;
    isCollectingMetadata: boolean;
}

export const useStoreMetadata = (): IUseStoreMetadata => {
    const [isCollectingMetadata, setIsCollectingMetadata] = useState(false);
    
    const collectMetadata = async (item: IStoreItem): Promise<Record<string, any> | null> => {
        if (!item.metadataType || item.metadataType === MetadataType.None) {
            return null;
        }

        setIsCollectingMetadata(true);
        
        try {
            // This is a promise-based approach that will be resolved when the MetadataCollector
            // component calls the onCollect or onCancel callbacks
            return await new Promise<Record<string, any> | null>((resolve) => {
                // We'll store the resolver functions in a global context
                // that will be accessible to the MetadataCollector component
                window.__metadataResolvers = {
                    resolve: (metadata: Record<string, any> | null) => {
                        resolve(metadata);
                    },
                    item,
                };
            });
        } finally {
            setIsCollectingMetadata(false);
            // Clean up the resolvers
            if (window.__metadataResolvers) {
                delete window.__metadataResolvers;
            }
        }
    };

    return {
        collectMetadata,
        isCollectingMetadata,
    };
};

// Add TypeScript declaration for the global object
declare global {
    interface Window {
        __metadataResolvers?: {
            resolve: (metadata: Record<string, any> | null) => void;
            item: IStoreItem;
        };
    }
}