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

const BackgroundImageSettingV3 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const responsiveEnabled = attributes.responsiveBackgroundImage !== undefined ? attributes.responsiveBackgroundImage : false;
  const { activeTab } = useResponsiveTab();

  const handleImageChange = (image) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundImagePC: image.url,
        backgroundImageSP: image.url,
      });
    } else {
      setAttributes({ [`backgroundImage${activeTab.toUpperCase()}`]: image.url });
    }
  };

  const handleFocalPointChange = (focalPoint) => {
    const { x, y } = focalPoint;
    const position = `${x * 100}% ${y * 100}%`;

    if (!responsiveEnabled) {
      setAttributes({
        backgroundImagePositionPC: position,
        backgroundImagePositionSP: position,
      });
    } else {
      setAttributes({ [`backgroundImagePosition${activeTab.toUpperCase()}`]: position });
    }
  };

  const handleImageSizeChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundImageSizePC: value,
        backgroundImageSizeSP: value,
      });

      if (value === "fill" || value === "none") {
        const widthPC = attributes.backgroundImageCustomWidthPC || "100";
        const heightPC = attributes.backgroundImageCustomHeightPC || "100";
        const widthUnitPC = attributes.backgroundImageCustomWidthUnitPC || "%";
        const heightUnitPC = attributes.backgroundImageCustomHeightUnitPC || "%";

        setAttributes({
          backgroundImageCustomWidthPC: widthPC,
          backgroundImageCustomHeightPC: heightPC,
          backgroundImageCustomWidthUnitPC: widthUnitPC,
          backgroundImageCustomHeightUnitPC: heightUnitPC,

          backgroundImageCustomWidthSP: widthPC,
          backgroundImageCustomHeightSP: heightPC,
          backgroundImageCustomWidthUnitSP: widthUnitPC,
          backgroundImageCustomHeightUnitSP: heightUnitPC,
        });
      }
    } else {
      setAttributes({ [`backgroundImageSize${activeTab.toUpperCase()}`]: value });

      if (value === "fill" || value === "none") {
        setAttributes({
          [`backgroundImageCustomWidth${activeTab.toUpperCase()}`]: attributes[`backgroundImageCustomWidth${activeTab.toUpperCase()}`] || "100",
          [`backgroundImageCustomHeight${activeTab.toUpperCase()}`]: attributes[`backgroundImageCustomHeight${activeTab.toUpperCase()}`] || "100",
          [`backgroundImageCustomWidthUnit${activeTab.toUpperCase()}`]: "%",
          [`backgroundImageCustomHeightUnit${activeTab.toUpperCase()}`]: "%",
        });
      }
    }
  };

  const handleCustomWidthChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          backgroundImageCustomWidthPC: value,
          backgroundImageCustomWidthSP: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          backgroundImageCustomWidthUnitPC: unit,
          backgroundImageCustomWidthUnitSP: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`backgroundImageCustomWidth${activeTab.toUpperCase()}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundImageCustomWidthUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handleCustomHeightChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          backgroundImageCustomHeightPC: value,
          backgroundImageCustomHeightSP: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          backgroundImageCustomHeightUnitPC: unit,
          backgroundImageCustomHeightUnitSP: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`backgroundImageCustomHeight${activeTab.toUpperCase()}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundImageCustomHeightUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handleRepeatChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundImageRepeatPC: value,
        backgroundImageRepeatSP: value,
      });
    } else {
      setAttributes({ [`backgroundImageRepeat${activeTab.toUpperCase()}`]: value });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ responsiveBackgroundImage: value });

    if (!value) {
      const syncAttrs = {};

      if (attributes.backgroundImagePC) {
        syncAttrs.backgroundImageSP = attributes.backgroundImagePC;
      }
      if (attributes.backgroundImagePositionPC) {
        syncAttrs.backgroundImagePositionSP = attributes.backgroundImagePositionPC;
      }
      if (attributes.backgroundImageSizePC) {
        syncAttrs.backgroundImageSizeSP = attributes.backgroundImageSizePC;
      }
      if (attributes.backgroundImageRepeatPC) {
        syncAttrs.backgroundImageRepeatSP = attributes.backgroundImageRepeatPC;
      }

      if (attributes.backgroundImageSizePC === "fill" || attributes.backgroundImageSizePC === "none") {
        syncAttrs.backgroundImageCustomWidthSP = attributes.backgroundImageCustomWidthPC;
        syncAttrs.backgroundImageCustomHeightSP = attributes.backgroundImageCustomHeightPC;
        syncAttrs.backgroundImageCustomWidthUnitSP = attributes.backgroundImageCustomWidthUnitPC;
        syncAttrs.backgroundImageCustomHeightUnitSP = attributes.backgroundImageCustomHeightUnitPC;
      }

      if (Object.keys(syncAttrs).length > 0) {
        setAttributes(syncAttrs);
      }
    }
  };

  const renderImageControls = () => {
    const imageUrl = attributes[`backgroundImage${activeTab.toUpperCase()}`];
    const imagePosition = attributes[`backgroundImagePosition${activeTab.toUpperCase()}`] || "50% 50%";
    const imageSize = attributes[`backgroundImageSize${activeTab.toUpperCase()}`] || "cover";
    const imageRepeat = attributes[`backgroundImageRepeat${activeTab.toUpperCase()}`] || "no-repeat";
    const customWidthRaw = attributes[`backgroundImageCustomWidth${activeTab.toUpperCase()}`];
    const customHeightRaw = attributes[`backgroundImageCustomHeight${activeTab.toUpperCase()}`];
    const customWidth = customWidthRaw === "auto" ? "auto" : (customWidthRaw || 100);
    const customHeight = customHeightRaw === "auto" ? "auto" : (customHeightRaw || 100);
    const customWidthUnit = attributes[`backgroundImageCustomWidthUnit${activeTab.toUpperCase()}`] || "%";
    const customHeightUnit = attributes[`backgroundImageCustomHeightUnit${activeTab.toUpperCase()}`] || "%";
    const isWidthAuto = customWidth === "auto";
    const isHeightAuto = customHeight === "auto";

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

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

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

        {imageUrl && (
          <div className="zenblocks-inspector-background-image__settings">
            <FocalPointPicker url={imageUrl} value={{ x, y }} onChange={handleFocalPointChange} />

            <SelectControl
              label={__("Repeat", "zenblocks")}
              value={imageRepeat}
              options={[
                { label: __("None", "zenblocks"), value: "no-repeat" },
                { label: __("Repeat", "zenblocks"), value: "repeat" },
                { label: __("Horizontal Only", "zenblocks"), value: "repeat-x" },
                { label: __("Vertical Only", "zenblocks"), value: "repeat-y" },
                { label: __("Space", "zenblocks"), value: "space" },
                { label: __("Round", "zenblocks"), value: "round" },
              ]}
              onChange={handleRepeatChange}
              className="zenblocks-inspector-background-image__repeat-select"
            />

            <SelectControl
              label={__("Fit Method", "zenblocks")}
              value={imageSize}
              options={[
                { label: __("Cover", "zenblocks"), value: "cover" },
                { label: __("Contain", "zenblocks"), value: "contain" },
                { label: __("Fill", "zenblocks"), value: "fill" },
                { label: __("None", "zenblocks"), value: "none" },
              ]}
              onChange={handleImageSizeChange}
              className="zenblocks-inspector-background-image__size-select"
            />

            {(imageSize === "fill" || imageSize === "none") && (
              <div className="zenblocks-inspector-background-image__custom-size" style={{ marginTop: "10px" }}>
                <div className="zenblocks-inspector-background-image__width-controls" style={{ marginBottom: "12px" }}>
                  <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>
                    {__("Width", "zenblocks")}
                  </label>
                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <div style={{ flex: 1, opacity: isWidthAuto ? 0.5 : 1, pointerEvents: isWidthAuto ? "none" : "auto" }}>
                      <UnitControl
                        value={isWidthAuto ? "" : `${customWidth}${customWidthUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "");
                          handleCustomWidthChange(numValue, unit || customWidthUnit);
                        }}
                        units={units}
                        placeholder={isWidthAuto ? "auto" : ""}
                      />
                    </div>
                    <Button
                      isSmall
                      variant={isWidthAuto ? "primary" : "secondary"}
                      onClick={() => {
                        if (isWidthAuto) {
                          handleCustomWidthChange(100, "%");
                        } else {
                          handleCustomWidthChange("auto", "");
                        }
                      }}
                      style={{ flexShrink: 0 }}
                    >
                      AUTO
                    </Button>
                  </div>
                </div>
                <div className="zenblocks-inspector-background-image__height-controls">
                  <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>
                    {__("Height", "zenblocks")}
                  </label>
                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <div style={{ flex: 1, opacity: isHeightAuto ? 0.5 : 1, pointerEvents: isHeightAuto ? "none" : "auto" }}>
                      <UnitControl
                        value={isHeightAuto ? "" : `${customHeight}${customHeightUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "");
                          handleCustomHeightChange(numValue, unit || customHeightUnit);
                        }}
                        units={units}
                        placeholder={isHeightAuto ? "auto" : ""}
                      />
                    </div>
                    <Button
                      isSmall
                      variant={isHeightAuto ? "primary" : "secondary"}
                      onClick={() => {
                        if (isHeightAuto) {
                          handleCustomHeightChange(100, "%");
                        } else {
                          handleCustomHeightChange("auto", "");
                        }
                      }}
                      style={{ flexShrink: 0 }}
                    >
                      AUTO
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl 
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveBackgroundImage"
      >
        {renderImageControls}
      </ResponsiveControl>
    </PanelBody>
  );
};

export default BackgroundImageSettingV3;
