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 CardStyleBackgroundImageSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  // PC/SP同期設定の状態
  const syncBackgroundImage = attributes.cardStyleSyncBackgroundImage !== undefined ? attributes.cardStyleSyncBackgroundImage : true;
  const { activeTab } = useResponsiveTab();

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

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

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

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

      if (value === "custom") {
        const widthPC = attributes.cardStyleBackgroundImageCustomWidthPC || "500";
        const heightPC = attributes.cardStyleBackgroundImageCustomHeightPC || "300";
        const widthUnitPC = attributes.cardStyleBackgroundImageCustomWidthUnitPC || "px";
        const heightUnitPC = attributes.cardStyleBackgroundImageCustomHeightUnitPC || "px";

        setAttributes({
          cardStyleBackgroundImageCustomWidthPC: widthPC,
          cardStyleBackgroundImageCustomHeightPC: heightPC,
          cardStyleBackgroundImageCustomWidthAutoPC: false,
          cardStyleBackgroundImageCustomHeightAutoPC: false,
          cardStyleBackgroundImageCustomWidthUnitPC: widthUnitPC,
          cardStyleBackgroundImageCustomHeightUnitPC: heightUnitPC,

          cardStyleBackgroundImageCustomWidthSP: widthPC,
          cardStyleBackgroundImageCustomHeightSP: heightPC,
          cardStyleBackgroundImageCustomWidthAutoSP: false,
          cardStyleBackgroundImageCustomHeightAutoSP: false,
          cardStyleBackgroundImageCustomWidthUnitSP: widthUnitPC,
          cardStyleBackgroundImageCustomHeightUnitSP: heightUnitPC,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`cardStyleBackgroundImageSize${activeTab.toUpperCase()}`]: value });

      if (value === "custom") {
        setAttributes({
          [`cardStyleBackgroundImageCustomWidth${activeTab.toUpperCase()}`]: attributes[`cardStyleBackgroundImageCustomWidth${activeTab.toUpperCase()}`] || "500",
          [`cardStyleBackgroundImageCustomHeight${activeTab.toUpperCase()}`]: attributes[`cardStyleBackgroundImageCustomHeight${activeTab.toUpperCase()}`] || "300",
          [`cardStyleBackgroundImageCustomWidthAuto${activeTab.toUpperCase()}`]: false,
          [`cardStyleBackgroundImageCustomHeightAuto${activeTab.toUpperCase()}`]: false,
          [`cardStyleBackgroundImageCustomWidthUnit${activeTab.toUpperCase()}`]: "px",
          [`cardStyleBackgroundImageCustomHeightUnit${activeTab.toUpperCase()}`]: "px",
        });
      }
    }
  };

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

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

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

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

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

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    if (value) {
      const syncAttrs = {};

      // ベース設定
      if (attributes.cardStyleBackgroundImagePC) {
        syncAttrs.cardStyleBackgroundImageSP = attributes.cardStyleBackgroundImagePC;
      }
      if (attributes.cardStyleBackgroundImagePositionPC) {
        syncAttrs.cardStyleBackgroundImagePositionSP = attributes.cardStyleBackgroundImagePositionPC;
      }
      if (attributes.cardStyleBackgroundImageSizePC) {
        syncAttrs.cardStyleBackgroundImageSizeSP = attributes.cardStyleBackgroundImageSizePC;
      }
      if (attributes.cardStyleBackgroundImageRepeatPC) {
        syncAttrs.cardStyleBackgroundImageRepeatSP = attributes.cardStyleBackgroundImageRepeatPC;
      }

      // カスタムサイズ関連
      if (attributes.cardStyleBackgroundImageSizePC === "custom") {
        syncAttrs.cardStyleBackgroundImageCustomWidthSP = attributes.cardStyleBackgroundImageCustomWidthPC;
        syncAttrs.cardStyleBackgroundImageCustomHeightSP = attributes.cardStyleBackgroundImageCustomHeightPC;
        syncAttrs.cardStyleBackgroundImageCustomWidthAutoSP = attributes.cardStyleBackgroundImageCustomWidthAutoPC;
        syncAttrs.cardStyleBackgroundImageCustomHeightAutoSP = attributes.cardStyleBackgroundImageCustomHeightAutoPC;
        syncAttrs.cardStyleBackgroundImageCustomWidthUnitSP = attributes.cardStyleBackgroundImageCustomWidthUnitPC;
        syncAttrs.cardStyleBackgroundImageCustomHeightUnitSP = attributes.cardStyleBackgroundImageCustomHeightUnitPC;
      }

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

  const renderImageControls = () => {
    const imageUrl = attributes[`cardStyleBackgroundImage${activeTab.toUpperCase()}`];
    const imagePosition = attributes[`cardStyleBackgroundImagePosition${activeTab.toUpperCase()}`] || "50% 50%";
    const imageSize = attributes[`cardStyleBackgroundImageSize${activeTab.toUpperCase()}`] || "cover";
    const imageRepeat = attributes[`cardStyleBackgroundImageRepeat${activeTab.toUpperCase()}`] || "no-repeat";
    const customWidth = attributes[`cardStyleBackgroundImageCustomWidth${activeTab.toUpperCase()}`] || "500";
    const customHeight = attributes[`cardStyleBackgroundImageCustomHeight${activeTab.toUpperCase()}`] || "300";
    const customWidthUnit = attributes[`cardStyleBackgroundImageCustomWidthUnit${activeTab.toUpperCase()}`] || "px";
    const customHeightUnit = attributes[`cardStyleBackgroundImageCustomHeightUnit${activeTab.toUpperCase()}`] || "px";
    const isWidthAuto = attributes[`cardStyleBackgroundImageCustomWidthAuto${activeTab.toUpperCase()}`];
    const isHeightAuto = attributes[`cardStyleBackgroundImageCustomHeightAuto${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={{ background: '#f0f0f0', padding: '10px', marginBottom: '10px', fontSize: '12px' }}>
        <strong>デバッグ情報:</strong><br/>
        PC背景画像: {attributes.cardStyleBackgroundImagePC || '未設定'}<br/>
        SP背景画像: {attributes.cardStyleBackgroundImageSP || '未設定'}<br/>
        同期設定: {syncBackgroundImage ? '有効' : '無効'}<br/>
        アクティブタブ: {activeTab}
      </div>
      <div style={{ paddingTop: "10px" }}>
        <ToggleControl
          label={__("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 CardStyleBackgroundImageSetting;
