import { MetadataType } from "@rpg-engine/shared";
import React, { useEffect } from "react";
import { CharacterSkinSelectionModal } from "../Character/CharacterSkinSelectionModal";

export interface IMetadataCollectorProps {
    metadataType: MetadataType;
    config: Record<string, any>;
    onCollect: (metadata: Record<string, any>) => void;
    onCancel: () => void;
}

export const MetadataCollector: React.FC<IMetadataCollectorProps> = ({
    metadataType,
    config,
    onCollect,
    onCancel,
}) => {
    // Make sure we clean up if unmounted without collecting
    useEffect(() => {
        return () => {
            // If we're unmounting without explicitly collecting or canceling,
            // make sure to call onCancel to prevent any hanging promises
            if (window.__metadataResolvers) {
                onCancel();
            }
        };
    }, [onCancel]);

    // Use string comparison instead of direct property access
    if (metadataType === 'CharacterSkin') {
        return (
            <CharacterSkinSelectionModal
                isOpen={true}
                onClose={onCancel}
                onConfirm={(selectedSkin: any) => onCollect({ selectedSkin })}
                availableCharacters={config.availableCharacters || []}
                atlasJSON={config.atlasJSON}
                atlasIMG={config.atlasIMG}
                initialSelectedSkin={config.initialSelectedSkin}
            />
        );
    } else {
        console.warn(`No collector implemented for metadata type: ${metadataType}`);
        // Auto-cancel for unhandled types to prevent hanging promises
        setTimeout(onCancel, 0);
        return null;
    }
};
