import { Button } from "@wordpress/components";
import { useState } from "@wordpress/element";

const MediaUploader = ({ handleChange, value = null }) => {
  const [image, setImage] = useState(value);
  const handleUpload = () => {
    console.log('uploading');
    const mediaUploader = wp.media({
      title: 'Upload Media',
      button: {
        text: 'Select Media'
      },
      multiple: false  // Set to true if you want to allow multiple files to be selected
    });

    mediaUploader.on('select', () => {
      const attachment = mediaUploader.state().get('selection').first().toJSON();
      // console.log(attachment);
      handleChange(attachment);
      setImage(attachment.url);
      // You can now use the 'attachment' object to process the selected media file
    });

    mediaUploader.open();
  };

  return (
    <div className="media-upload-control">
        <div className={`media-preview ${image? 'no-border' : ''}`}>
            { !image && <span>Upload an image</span> }
            { image && <img src={image} alt={'shopbuild'} /> }
        </div>
        <Button isPrimary onClick={handleUpload}>
            { image ? 'Change Image' : 'Upload Image' }
        </Button>
    </div>
  );
};

export default MediaUploader;
