import { Button, SelectControl, FocalPointPicker } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const BackgroundImageSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "responsiveBackgroundImageHover" : "responsiveBackgroundImage";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const handleImageChange = (image) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundImage${bp.toUpperCase()}${hoverSuffix}`] = image.url;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundImage${deviceSuffix}${hoverSuffix}`]: image.url });
    }
  };

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

    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundImagePosition${bp.toUpperCase()}${hoverSuffix}`] = position;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundImagePosition${deviceSuffix}${hoverSuffix}`]: position });
    }
  };

  const handleImageSizeChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundImageSize${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);

      if (value === "fill" || value === "none") {
        const widthPC = attributes[`backgroundImageCustomWidthPC${hoverSuffix}`] || "100";
        const heightPC = attributes[`backgroundImageCustomHeightPC${hoverSuffix}`] || "100";
        const widthUnitPC = attributes[`backgroundImageCustomWidthUnitPC${hoverSuffix}`] || "%";
        const heightUnitPC = attributes[`backgroundImageCustomHeightUnitPC${hoverSuffix}`] || "%";

        const customUpdates = {};
        enabledBreakpoints.forEach((bp) => {
          customUpdates[`backgroundImageCustomWidth${bp.toUpperCase()}${hoverSuffix}`] = widthPC;
          customUpdates[`backgroundImageCustomHeight${bp.toUpperCase()}${hoverSuffix}`] = heightPC;
          customUpdates[`backgroundImageCustomWidthUnit${bp.toUpperCase()}${hoverSuffix}`] = widthUnitPC;
          customUpdates[`backgroundImageCustomHeightUnit${bp.toUpperCase()}${hoverSuffix}`] = heightUnitPC;
        });
        setAttributes(customUpdates);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundImageSize${deviceSuffix}${hoverSuffix}`]: value });

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

  const handleCustomWidthChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundImageCustomWidth${bp.toUpperCase()}${hoverSuffix}`] = value;
        });
        setAttributes(updates);
      }
      if (unit !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundImageCustomWidthUnit${bp.toUpperCase()}${hoverSuffix}`] = unit;
        });
        setAttributes(updates);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      if (value !== undefined) {
        setAttributes({ [`backgroundImageCustomWidth${deviceSuffix}${hoverSuffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundImageCustomWidthUnit${deviceSuffix}${hoverSuffix}`]: unit });
      }
    }
  };

  const handleCustomHeightChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundImageCustomHeight${bp.toUpperCase()}${hoverSuffix}`] = value;
        });
        setAttributes(updates);
      }
      if (unit !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundImageCustomHeightUnit${bp.toUpperCase()}${hoverSuffix}`] = unit;
        });
        setAttributes(updates);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      if (value !== undefined) {
        setAttributes({ [`backgroundImageCustomHeight${deviceSuffix}${hoverSuffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundImageCustomHeightUnit${deviceSuffix}${hoverSuffix}`]: unit });
      }
    }
  };

  const handleRepeatChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundImageRepeat${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundImageRepeat${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

    const syncAttrs = {};
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`backgroundImage${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImagePC${hoverSuffix}`];
        syncAttrs[`backgroundImagePosition${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImagePositionPC${hoverSuffix}`];
        syncAttrs[`backgroundImageSize${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageSizePC${hoverSuffix}`];
        syncAttrs[`backgroundImageRepeat${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageRepeatPC${hoverSuffix}`];
      }
    });

    const imageSize = attributes[`backgroundImageSizePC${hoverSuffix}`];
    if (imageSize === "fill" || imageSize === "none") {
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          syncAttrs[`backgroundImageCustomWidth${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageCustomWidthPC${hoverSuffix}`];
          syncAttrs[`backgroundImageCustomHeight${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageCustomHeightPC${hoverSuffix}`];
          syncAttrs[`backgroundImageCustomWidthUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageCustomWidthUnitPC${hoverSuffix}`];
          syncAttrs[`backgroundImageCustomHeightUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundImageCustomHeightUnitPC${hoverSuffix}`];
        }
      });
    }

    setAttributes(syncAttrs);
  };

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

  const content = (
    <ResponsiveControlV2
      initialOpen={true}
      enableResponsiveToggle={true}
      responsiveEnabled={responsiveEnabled}
      onResponsiveToggle={handleResponsiveToggle}
      attributes={attributes}
      setAttributes={setAttributes}
      syncAttributeName={responsiveAttrName}
    >
      {(tabName) => renderImageControls(tabName)}
    </ResponsiveControlV2>
  );

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="background-image">
      {isPro ? <ProFeatureOverlay featureName="背景画像">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export default BackgroundImageSettingV5;
