import { PanelBody, Button, SelectControl, ToggleControl } 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";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";

const BackgroundImageSettingV2 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  // PC/SP同期設定の状態
  const syncBackgroundImage = attributes.syncBackgroundImage !== undefined ? attributes.syncBackgroundImage : true;
  const { activeTab } = useResponsiveTab();

  const handleImageChange = (image) => {
    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundImagePC: image.url,
        backgroundImageSP: image.url,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundImage${activeTab.toUpperCase()}`]: image.url });
    }
  };

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

    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundImagePositionPC: position,
        backgroundImagePositionSP: position,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundImagePosition${activeTab.toUpperCase()}`]: position });
    }
  };

  const handleImageSizeChange = (value) => {
    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundImageSizePC: value,
        backgroundImageSizeSP: value,
      });

      if (value === "custom") {
        const widthPC = attributes.backgroundImageCustomWidthPC || "500";
        const heightPC = attributes.backgroundImageCustomHeightPC || "300";
        const widthUnitPC = attributes.backgroundImageCustomWidthUnitPC || "px";
        const heightUnitPC = attributes.backgroundImageCustomHeightUnitPC || "px";

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

          backgroundImageCustomWidthSP: widthPC,
          backgroundImageCustomHeightSP: heightPC,
          backgroundImageCustomWidthAutoSP: false,
          backgroundImageCustomHeightAutoSP: false,
          backgroundImageCustomWidthUnitSP: widthUnitPC,
          backgroundImageCustomHeightUnitSP: heightUnitPC,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundImageSize${activeTab.toUpperCase()}`]: value });

      if (value === "custom") {
        setAttributes({
          [`backgroundImageCustomWidth${activeTab.toUpperCase()}`]: attributes[`backgroundImageCustomWidth${activeTab.toUpperCase()}`] || "500",
          [`backgroundImageCustomHeight${activeTab.toUpperCase()}`]: attributes[`backgroundImageCustomHeight${activeTab.toUpperCase()}`] || "300",
          [`backgroundImageCustomWidthAuto${activeTab.toUpperCase()}`]: false,
          [`backgroundImageCustomHeightAuto${activeTab.toUpperCase()}`]: false,
          [`backgroundImageCustomWidthUnit${activeTab.toUpperCase()}`]: "px",
          [`backgroundImageCustomHeightUnit${activeTab.toUpperCase()}`]: "px",
        });
      }
    }
  };

  const handleCustomSizeChange = (property, value, unit) => {
    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      if (value !== undefined) {
        setAttributes({
          [`backgroundImageCustom${property}PC`]: value.toString(),
          [`backgroundImageCustom${property}SP`]: value.toString(),
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`backgroundImageCustom${property}UnitPC`]: unit,
          [`backgroundImageCustom${property}UnitSP`]: unit,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      if (value !== undefined) {
        setAttributes({ [`backgroundImageCustom${property}${activeTab.toUpperCase()}`]: value.toString() });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundImageCustom${property}Unit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handleAutoSizeToggle = (property) => {
    const currentValue = attributes[`backgroundImageCustom${property}Auto${activeTab.toUpperCase()}`];

    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        [`backgroundImageCustom${property}AutoPC`]: !currentValue,
        [`backgroundImageCustom${property}AutoSP`]: !currentValue,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundImageCustom${property}Auto${activeTab.toUpperCase()}`]: !currentValue });
    }
  };

  const handleRepeatChange = (value) => {
    if (syncBackgroundImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundImageRepeatPC: value,
        backgroundImageRepeatSP: value,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundImageRepeat${activeTab.toUpperCase()}`]: value });
    }
  };

  // 同期設定の切り替え
  const handleSyncToggle = (value) => {
    setAttributes({ syncBackgroundImage: value });

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    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 === "custom") {
        syncAttrs.backgroundImageCustomWidthSP = attributes.backgroundImageCustomWidthPC;
        syncAttrs.backgroundImageCustomHeightSP = attributes.backgroundImageCustomHeightPC;
        syncAttrs.backgroundImageCustomWidthAutoSP = attributes.backgroundImageCustomWidthAutoPC;
        syncAttrs.backgroundImageCustomHeightAutoSP = attributes.backgroundImageCustomHeightAutoPC;
        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 customWidth = attributes[`backgroundImageCustomWidth${activeTab.toUpperCase()}`] || "500";
    const customHeight = attributes[`backgroundImageCustomHeight${activeTab.toUpperCase()}`] || "300";
    const customWidthUnit = attributes[`backgroundImageCustomWidthUnit${activeTab.toUpperCase()}`] || "px";
    const customHeightUnit = attributes[`backgroundImageCustomHeightUnit${activeTab.toUpperCase()}`] || "px";
    const isWidthAuto = attributes[`backgroundImageCustomWidthAuto${activeTab.toUpperCase()}`];
    const isHeightAuto = attributes[`backgroundImageCustomHeightAuto${activeTab.toUpperCase()}`];

    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="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 Repeat", "zenblocks")}
              value={imageRepeat}
              options={[
                { label: __("No Repeat", "zenblocks"), value: "no-repeat" },
                { label: __("Repeat", "zenblocks"), value: "repeat" },
                { label: __("Repeat X", "zenblocks"), value: "repeat-x" },
                { label: __("Repeat Y", "zenblocks"), value: "repeat-y" },
                { label: __("Space", "zenblocks"), value: "space" },
                { label: __("Round", "zenblocks"), value: "round" },
              ]}
              onChange={handleRepeatChange}
              className="background-repeat-select"
            />

            <SelectControl
              label={__("Background Size", "zenblocks")}
              value={imageSize}
              options={[
                { label: __("Cover", "zenblocks"), value: "cover" },
                { label: __("Contain", "zenblocks"), value: "contain" },
                { label: __("Auto", "zenblocks"), value: "auto" },
                { label: __("Custom", "zenblocks"), value: "custom" },
              ]}
              onChange={handleImageSizeChange}
              className="background-size-select"
            />

            {imageSize === "custom" && (
              <div className="custom-size-controls">
                <div className="width-controls">
                  <ToggleControl label={__("Width Auto", "zenblocks")} checked={isWidthAuto} onChange={() => handleAutoSizeToggle("Width")} />
                  {!isWidthAuto && (
                    <div className="unit-control-wrapper">
                      <UnitControl
                        label={__("Width", "zenblocks")}
                        value={`${customWidth}${customWidthUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "");
                          handleCustomSizeChange("Width", numValue, unit || customWidthUnit);
                        }}
                        units={units}
                      />
                    </div>
                  )}
                </div>
                <div className="height-controls">
                  <ToggleControl label={__("Height Auto", "zenblocks")} checked={isHeightAuto} onChange={() => handleAutoSizeToggle("Height")} />
                  {!isHeightAuto && (
                    <div className="unit-control-wrapper">
                      <UnitControl
                        label={__("Height", "zenblocks")}
                        value={`${customHeight}${customHeightUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "");
                          handleCustomSizeChange("Height", numValue, unit || customHeightUnit);
                        }}
                        units={units}
                      />
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <div style={{ paddingTop: "10px" }}>
        <ToggleControl
          label={__("PC/SP Sync Settings", "zenblocks")}
          checked={syncBackgroundImage}
          onChange={handleSyncToggle}
          // help={syncBackgroundImage ? __('PC settings are automatically applied to SP', 'zenblocks') : __('PC and SP can be set individually', 'zenblocks')}
        />
      </div>
      <ResponsiveControl initialOpen={true}>{renderImageControls}</ResponsiveControl>
      {syncBackgroundImage && activeTab === "sp" && (
        <div style={{ padding: "10px", backgroundColor: "#f0f0f0", marginTop: "10px", borderRadius: "4px" }}>{__("In sync mode, PC settings are applied.", "zenblocks")}</div>
      )}
    </PanelBody>
  );
};

export default BackgroundImageSettingV2;
