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

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

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

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

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

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

  const resetPattern = () => {
    if (syncBackgroundPattern && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundPatternTypePC: "none",
        backgroundPatternColorPC: "#000000",
        backgroundPatternOpacityPC: 0.1,
        backgroundPatternSizePC: 20,
        backgroundPatternSizeUnitPC: "px",
        backgroundPatternRotatePC: 0,

        backgroundPatternTypeSP: "none",
        backgroundPatternColorSP: "#000000",
        backgroundPatternOpacitySP: 0.1,
        backgroundPatternSizeSP: 20,
        backgroundPatternSizeUnitSP: "px",
        backgroundPatternRotateSP: 0,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({
        [`backgroundPatternType${activeTab.toUpperCase()}`]: "none",
        [`backgroundPatternColor${activeTab.toUpperCase()}`]: "#000000",
        [`backgroundPatternOpacity${activeTab.toUpperCase()}`]: 0.1,
        [`backgroundPatternSize${activeTab.toUpperCase()}`]: 20,
        [`backgroundPatternSizeUnit${activeTab.toUpperCase()}`]: "px",
        [`backgroundPatternRotate${activeTab.toUpperCase()}`]: 0,
      });
    }
  };

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

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    if (value) {
      setAttributes({
        backgroundPatternTypeSP: attributes.backgroundPatternTypePC,
        backgroundPatternColorSP: attributes.backgroundPatternColorPC,
        backgroundPatternOpacitySP: attributes.backgroundPatternOpacityPC,
        backgroundPatternSizeSP: attributes.backgroundPatternSizePC,
        backgroundPatternSizeUnitSP: attributes.backgroundPatternSizeUnitPC,
        backgroundPatternRotateSP: attributes.backgroundPatternRotatePC,
      });
    }
  };

  const renderPatternControls = (tabName) => {
    const patternType = attributes[`backgroundPatternType${tabName.toUpperCase()}`] || "none";
    const patternColor = attributes[`backgroundPatternColor${tabName.toUpperCase()}`] || "#000000";
    const patternOpacity = attributes[`backgroundPatternOpacity${tabName.toUpperCase()}`] || 0.1;
    const patternSize = attributes[`backgroundPatternSize${tabName.toUpperCase()}`] || 20;
    const patternSizeUnit = attributes[`backgroundPatternSizeUnit${tabName.toUpperCase()}`] || "px";
    const patternRotate = attributes[`backgroundPatternRotate${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 BackgroundPatternSetting;
