import React from 'react';
import { __ } from '@wordpress/i18n';
import { PanelBody, Button } from '@wordpress/components';
import { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';

const ImageSetting = ({ attributes, setAttributes, panelTitle = __('Image Settings', 'zenblocks') }) => {
    const { imageUrl, imageId, imageAlt } = attributes;

    const onSelectImage = (media) => {
        setAttributes({
            imageUrl: media.url,
            imageId: media.id,
            imageAlt: media.alt || ''
        });
    };

    const onRemoveImage = () => {
        setAttributes({
            imageUrl: '',
            imageId: null,
            imageAlt: ''
        });
    };

    return (
        <PanelBody
            title={panelTitle}
            initialOpen={false}
        >
            <div className="media-upload-container" style={{ marginBottom: '15px' }}>
                <div style={{ marginBottom: '10px' }}>
                    {imageUrl && (
                        <img 
                            src={imageUrl} 
                            alt={imageAlt || ''} 
                            style={{ 
                                maxWidth: '100%', 
                                height: 'auto', 
                                maxHeight: '150px', 
                                marginBottom: '10px' 
                            }} 
                        />
                    )}
                </div>
                <MediaUploadCheck>
                    <MediaUpload
                        onSelect={onSelectImage}
                        allowedTypes={['image']}
                        value={imageId}
                        render={({ open }) => (
                            <div style={{ display: 'flex', gap: '10px' }}>
                                <Button onClick={open} variant="secondary">
                                    {imageUrl ? __('Change Image', 'zenblocks') : __('Select Image', 'zenblocks')}
                                </Button>
                                {imageUrl && (
                                    <Button isDestructive onClick={onRemoveImage}>
                                        {__('Remove Image', 'zenblocks')}
                                    </Button>
                                )}
                            </div>
                        )}
                    />
                </MediaUploadCheck>
            </div>
        </PanelBody>
    );
};

export default ImageSetting;
