import { PanelBody, SelectControl, RangeControl, Button, ToggleControl } from "@wordpress/components";
import { ColorPicker } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";

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

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

  const handlePatternColorChange = (color) => {
    if (syncBackgroundPattern && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        cardStyleBackgroundPatternColorPC: color.hex,
        cardStyleBackgroundPatternColorSP: color.hex,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`cardStyleBackgroundPatternColor${activeTab.toUpperCase()}`]: color.hex });
    }
  };

  const handlePatternOpacityChange = (value) => {
    // 明示的に数値として設定
    const numericValue = Number(value);
    if (syncBackgroundPattern && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        cardStyleBackgroundPatternOpacityPC: numericValue,
        cardStyleBackgroundPatternOpacitySP: numericValue,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`cardStyleBackgroundPatternOpacity${activeTab.toUpperCase()}`]: numericValue });
    }
  };

  const handlePatternSizeChange = (value, unit) => {
    if (syncBackgroundPattern && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      if (value !== undefined) {
        setAttributes({
          cardStyleBackgroundPatternSizePC: value,
          cardStyleBackgroundPatternSizeSP: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          cardStyleBackgroundPatternSizeUnitPC: unit,
          cardStyleBackgroundPatternSizeUnitSP: unit,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      if (value !== undefined) {
        setAttributes({ [`cardStyleBackgroundPatternSize${activeTab.toUpperCase()}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`cardStyleBackgroundPatternSizeUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

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

  const resetPattern = () => {
    if (syncBackgroundPattern && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        cardStyleBackgroundPatternTypePC: "none",
        cardStyleBackgroundPatternColorPC: "#000000",
        cardStyleBackgroundPatternOpacityPC: 0.1,
        cardStyleBackgroundPatternSizePC: 20,
        cardStyleBackgroundPatternSizeUnitPC: "px",
        cardStyleBackgroundPatternRotatePC: 0,

        cardStyleBackgroundPatternTypeSP: "none",
        cardStyleBackgroundPatternColorSP: "#000000",
        cardStyleBackgroundPatternOpacitySP: 0.1,
        cardStyleBackgroundPatternSizeSP: 20,
        cardStyleBackgroundPatternSizeUnitSP: "px",
        cardStyleBackgroundPatternRotateSP: 0,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({
        [`cardStyleBackgroundPatternType${activeTab.toUpperCase()}`]: "none",
        [`cardStyleBackgroundPatternColor${activeTab.toUpperCase()}`]: "#000000",
        [`cardStyleBackgroundPatternOpacity${activeTab.toUpperCase()}`]: 0.1,
        [`cardStyleBackgroundPatternSize${activeTab.toUpperCase()}`]: 20,
        [`cardStyleBackgroundPatternSizeUnit${activeTab.toUpperCase()}`]: "px",
        [`cardStyleBackgroundPatternRotate${activeTab.toUpperCase()}`]: 0,
      });
    }
  };

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

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    if (value) {
      setAttributes({
        cardStyleBackgroundPatternTypeSP: attributes.cardStyleBackgroundPatternTypePC,
        cardStyleBackgroundPatternColorSP: attributes.cardStyleBackgroundPatternColorPC,
        cardStyleBackgroundPatternOpacitySP: attributes.cardStyleBackgroundPatternOpacityPC,
        cardStyleBackgroundPatternSizeSP: attributes.cardStyleBackgroundPatternSizePC,
        cardStyleBackgroundPatternSizeUnitSP: attributes.cardStyleBackgroundPatternSizeUnitPC,
        cardStyleBackgroundPatternRotateSP: attributes.cardStyleBackgroundPatternRotatePC,
      });
    }
  };

  const renderPatternControls = (tabName) => {
    const patternType = attributes[`cardStyleBackgroundPatternType${tabName.toUpperCase()}`] || "none";
    const patternColor = attributes[`cardStyleBackgroundPatternColor${tabName.toUpperCase()}`] || "#000000";
    const patternOpacity = attributes[`cardStyleBackgroundPatternOpacity${tabName.toUpperCase()}`] || 0.1;
    const patternSize = attributes[`cardStyleBackgroundPatternSize${tabName.toUpperCase()}`] || 20;
    const patternSizeUnit = attributes[`cardStyleBackgroundPatternSizeUnit${tabName.toUpperCase()}`] || "px";
    const patternRotate = attributes[`cardStyleBackgroundPatternRotate${tabName.toUpperCase()}`] || 0;

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

    return (
      <div className="background-pattern-controls">
        <SelectControl
          label={__("Pattern Type", "zenblocks")}
          value={patternType}
          options={[
            { label: __("None", "zenblocks"), value: "none" },
            { label: __("Dots", "zenblocks"), value: "dots" },
            { label: __("Diagonal Lines", "zenblocks"), value: "diagonal-lines" },
            { label: __("Cross Lines", "zenblocks"), value: "cross-lines" },
            { label: __("Horizontal Lines", "zenblocks"), value: "horizontal-lines" },
            { label: __("Vertical Lines", "zenblocks"), value: "vertical-lines" },
            { label: __("Grid", "zenblocks"), value: "grid" },
            { label: __("Diagonal Grid", "zenblocks"), value: "diagonal-grid" },
            { label: __("Circles", "zenblocks"), value: "circles" },
            { label: __("Triangles", "zenblocks"), value: "triangles" },
          ]}
          onChange={handlePatternTypeChange}
        />

        {patternType !== "none" && (
          <>
            <div className="color-picker-wrapper">
              <label>{__("Pattern Color", "zenblocks")}</label>
              <ColorPicker color={patternColor} onChangeComplete={handlePatternColorChange} disableAlpha />
            </div>

            <RangeControl label={__("Pattern Opacity", "zenblocks")} value={patternOpacity} onChange={handlePatternOpacityChange} min={0} max={1} step={0.05} />

            <div className="unit-control-wrapper">
              <UnitControl
                label={__("Pattern Size", "zenblocks")}
                value={`${patternSize}${patternSizeUnit}`}
                onChange={(value) => {
                  const numValue = parseFloat(value);
                  const unit = value.replace(/[\d.-]/g, "");
                  handlePatternSizeChange(numValue, unit || patternSizeUnit);
                }}
                units={units}
              />
            </div>

            <RangeControl label={__("Pattern Rotation", "zenblocks")} value={patternRotate} onChange={handlePatternRotateChange} min={0} max={360} step={1} />

            <Button isSecondary onClick={resetPattern} style={{ marginTop: "10px" }}>
              {__("Reset Pattern", "zenblocks")}
            </Button>
          </>
        )}
      </div>
    );
  };

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

export default CardStyleBackgroundPatternSetting;
