export default function Uploader({media, onChange}) {

    const openUploader = (e) => {
        e.preventDefault();


        // Create the media frame.
        const file_frame = wp.media.frames.file_frame = wp.media({
            title: wp.i18n.__('Insert image', 'radio-player'),
            library: {
                type: 'image'
            },
            button: {
                text: wp.i18n.__('Insert', 'radio-player'),
            },
            multiple: false
        });

        file_frame.on('select', () => {

            const attachment = file_frame.state().get('selection').first().toJSON();

            onChange(attachment.url);
        });

        // Finally, open the modal
        file_frame.open();
    }

    const deleteMedia = (e) => {
        e.preventDefault();

        onChange('')
    }

    const isPro = radioPlayer.isPro;

    return (
        <div className={`upload-input-wrap thumbnail-uploader-wrap ${!isPro ? 'disabled' : ''}`}>
            {media && <img src={media} className="thumbnail-preview"/>}

            <input type="text"
                   id="thumbnail"
                   name="thumbnail"
                   placeholder={wp.i18n.__('Enter image url or select image', 'radio-player')}
                   value={media}
                   onChange={e => onChange(e.target.value)}
            />

            <button type={'button'} className="button select-file-btn radio_player_select_img" onClick={openUploader}>
                <i className="dashicons dashicons-upload"> </i>
            </button>

            {media &&
                <button type={'button'} className="button remove-file-btn radio_player_delete_img" onClick={deleteMedia}>
                    <i className="dashicons dashicons-trash"> </i>
                </button>
            }
        </div>
    )

}