import { PanelBody, Button, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { FocalPointPicker } from '@wordpress/components';
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

const BackgroundImageSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

  const handleImageChange = (image) => {
    setAttributes({ [`backgroundImage${activeTab.toUpperCase()}`]: image.url });

    // If SP image is empty and PC image is being set, also set SP image
    if (activeTab === 'pc' && !attributes.backgroundImageSP) {
      setAttributes({ backgroundImageSP: image.url });
    }
  };

  const handleFocalPointChange = (focalPoint) => {
    const { x, y } = focalPoint;
    setAttributes({ [`backgroundImagePosition${activeTab.toUpperCase()}`]: `${x * 100}% ${y * 100}%` });
  };

  const handleImageSizeChange = (value) => {
    setAttributes({ [`backgroundImageSize${activeTab.toUpperCase()}`]: value });
  };

  const renderImageControls = () => {
    const imageUrl = attributes[`backgroundImage${activeTab.toUpperCase()}`];
    const imagePosition = attributes[`backgroundImagePosition${activeTab.toUpperCase()}`] || '50% 50%';
    const imageSize = attributes[`backgroundImageSize${activeTab.toUpperCase()}`] || 'cover';

    const [x, y] = imagePosition.split(' ').map((val) => parseFloat(val) / 100);

    return (
      <div className="background-image-controls">
        <div className="button-container">
          <MediaUploadCheck>
            <MediaUpload
              onSelect={handleImageChange}
              allowedTypes={['image']}
              value={imageUrl}
              render={({ open }) => (
                <Button onClick={open} isPrimary className="set-image-button">
                  {imageUrl ? __('Change Image', 'zenblocks') : __('Set Image', 'zenblocks')}
                </Button>
              )}
            />
          </MediaUploadCheck>
          {imageUrl && (
            <Button isSecondary onClick={() => handleImageChange({ url: '' })} className="remove-image-button">
              {__('Remove Image', 'zenblocks')}
            </Button>
          )}
        </div>

        {imageUrl && (
          <div className="image-settings">
            <FocalPointPicker url={imageUrl} value={{ x, y }} onChange={handleFocalPointChange} />
            <SelectControl
              label={__('Background Size', 'zenblocks')}
              value={imageSize}
              options={[
                { label: __('Cover', 'zenblocks'), value: 'cover' },
                { label: __('Contain', 'zenblocks'), value: 'contain' },
                { label: __('Auto', 'zenblocks'), value: 'auto' },
              ]}
              onChange={handleImageSizeChange}
              className="background-size-select"
            />
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{renderImageControls}</ResponsiveControl>
    </PanelBody>
  );
};

export default BackgroundImageSetting;
