import React, { useState } from 'react';
import wordPressMediaManager from '../utils/wordpressMedia';
import ajaxApi from '../services/ajaxApi';

const WordPressMedia = ({ 
    onSelect, 
    multiple = false, 
    type = 'image', 
    buttonText = 'Select Media',
    className = '',
    children 
}) => {
    const [isOpen, setIsOpen] = useState(false);

    const openMediaLibrary = async () => {
        try {
            // Ensure media scripts are enqueued
            await ajaxApi.enqueueMediaScripts();
            
            // Debug media library status
            const status = wordPressMediaManager.debugStatus();
            
            const options = {
                title: multiple ? 'Select Media Files' : 'Select Media File',
                button: { text: buttonText },
                multiple: multiple,
                library: { type: type }
            };

            const result = await wordPressMediaManager.openMediaLibrary(options);
            
            console.log('Media library result:', result);
            
            if (result && result !== null) {
                onSelect(result);
            } else {
                console.warn('Media library returned null, falling back to file picker');
                openFallbackFilePicker();
            }
        } catch (error) {
            console.warn('WordPress media library error:', error.message);
            console.warn('Falling back to file picker');
            openFallbackFilePicker();
        }
    };

    const openFallbackFilePicker = () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.multiple = multiple;
        
        if (type === 'image') {
            input.accept = 'image/*';
        } else if (type === 'video') {
            input.accept = 'video/*';
        } else {
            input.accept = '*/*';
        }

        input.onchange = async (e) => {
            const files = Array.from(e.target.files);
            
            if (multiple) {
                const uploadPromises = files.map(file => uploadFileViaAjax(file));
                try {
                    const attachments = await Promise.all(uploadPromises);
                    onSelect(attachments);
                } catch (error) {
                    console.error('File upload failed:', error);
                    // Fallback to local file URLs
                    const filePromises = files.map(file => {
                        return new Promise((resolve) => {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                resolve({
                                    id: Date.now() + Math.random(),
                                    url: e.target.result,
                                    filename: file.name,
                                    alt: '',
                                    caption: '',
                                    title: file.name,
                                    mime: file.type,
                                    file: file
                                });
                            };
                            reader.readAsDataURL(file);
                        });
                    });

                    Promise.all(filePromises).then(attachments => {
                        onSelect(attachments);
                    });
                }
            } else {
                const file = files[0];
                if (file) {
                    try {
                        const attachment = await uploadFileViaAjax(file);
                        onSelect(attachment);
                    } catch (error) {
                        console.error('File upload failed:', error);
                        // Fallback to local file URL
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            onSelect({
                                id: Date.now(),
                                url: e.target.result,
                                filename: file.name,
                                alt: '',
                                caption: '',
                                title: file.name,
                                mime: file.type,
                                file: file
                            });
                        };
                        reader.readAsDataURL(file);
                    }
                }
            }
        };

        input.click();
    };

    const uploadFileViaAjax = async (file) => {
        try {
            const result = await ajaxApi.uploadProductImage(file);
            return {
                id: result.id,
                url: result.url,
                filename: result.filename,
                alt: result.alt || '',
                caption: result.caption || '',
                title: result.title || file.name,
                mime: result.mime || file.type,
                width: result.width || 0,
                height: result.height || 0
            };
        } catch (error) {
            console.error('Ajax upload failed:', error);
            throw error;
        }
    };

    if (children) {
        return (
            <div className={className} onClick={openMediaLibrary}>
                {children}
            </div>
        );
    }

    return (
        <button
            type="button"
            className={`btn btn-secondary ${className}`}
            onClick={openMediaLibrary}
        >
            {buttonText}
        </button>
    );
};

export default WordPressMedia;