import { __ } from "@wordpress/i18n";
import { useEffect } from "@wordpress/element";
import { SelectControl, RangeControl, ButtonGroup, Button, __experimentalNumberControl as NumberControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultLayoutPosition = () => ({
  pc: {
    type: "relative",
    useCustom: false,
    top: "auto",
    topUnit: "px",
    right: "auto",
    rightUnit: "px",
    bottom: "auto",
    bottomUnit: "px",
    left: "auto",
    leftUnit: "px",
    zIndex: "auto",
    translateX: 0,
    translateXUnit: "%",
    translateY: 0,
    translateYUnit: "%",
  },
  md: {
    type: "",
    useCustom: "",
    top: "",
    topUnit: "",
    right: "",
    rightUnit: "",
    bottom: "",
    bottomUnit: "",
    left: "",
    leftUnit: "",
    zIndex: "",
    translateX: "",
    translateXUnit: "",
    translateY: "",
    translateYUnit: "",
  },
  tb: {
    type: "",
    useCustom: "",
    top: "",
    topUnit: "",
    right: "",
    rightUnit: "",
    bottom: "",
    bottomUnit: "",
    left: "",
    leftUnit: "",
    zIndex: "",
    translateX: "",
    translateXUnit: "",
    translateY: "",
    translateYUnit: "",
  },
  sp: {
    type: "",
    useCustom: "",
    top: "",
    topUnit: "",
    right: "",
    rightUnit: "",
    bottom: "",
    bottomUnit: "",
    left: "",
    leftUnit: "",
    zIndex: "",
    translateX: "",
    translateXUnit: "",
    translateY: "",
    translateYUnit: "",
  },
});

const LayoutPositionSettingV7 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  isPro = false,
  learnMorePath = "",
}) => {
  const attrName = "layoutPositionV2";
  const responsiveAttrName = "useResponsiveLayoutPosition";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const enabledBreakpoints = getEnabledBreakpoints();

  const positionData = attributes[attrName] || getDefaultLayoutPosition();

  // layoutPositionV2に値があるのにis-custom-positionクラス用フラグが未設定の場合に同期
  useEffect(() => {
    const syncAttrs = {};
    enabledBreakpoints.forEach((bp) => {
      const key = `layoutUseCustomPosition${bp.toUpperCase()}`;
      if (!attributes[key]) {
        const bpData = positionData[bp];
        const hasCustomValue = bpData && (
          (bpData.type && bpData.type !== "" && bpData.type !== "relative") ||
          (bpData.top !== "auto" && bpData.top !== "" && bpData.top !== undefined) ||
          (bpData.right !== "auto" && bpData.right !== "" && bpData.right !== undefined) ||
          (bpData.bottom !== "auto" && bpData.bottom !== "" && bpData.bottom !== undefined) ||
          (bpData.left !== "auto" && bpData.left !== "" && bpData.left !== undefined) ||
          (bpData.zIndex !== "auto" && bpData.zIndex !== "" && bpData.zIndex !== undefined) ||
          (bpData.translateX !== 0 && bpData.translateX !== "" && bpData.translateX !== undefined) ||
          (bpData.translateY !== 0 && bpData.translateY !== "" && bpData.translateY !== undefined)
        );
        if (hasCustomValue) {
          syncAttrs[key] = true;
        }
      }
    });
    if (Object.keys(syncAttrs).length > 0) {
      setAttributes(syncAttrs);
    }
  }, []);

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

  const handleChange = (key, value, currentTab = "pc") => {
    const newData = JSON.parse(JSON.stringify(positionData));
    const attrs = {};
    if (responsiveEnabled) {
      newData[currentTab][key] = value;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newData[bp][key] = value;
      });
    }
    attrs[attrName] = newData;

    // is-custom-positionクラス用フラグを連動
    // 変更後のデータでカスタム値があるかチェック
    const checkBps = responsiveEnabled ? [currentTab] : enabledBreakpoints;
    checkBps.forEach((bp) => {
      const bpData = newData[bp];
      const hasCustomValue = (
        (bpData.type && bpData.type !== "" && bpData.type !== "relative") ||
        (bpData.top !== "auto" && bpData.top !== "" && bpData.top !== undefined) ||
        (bpData.right !== "auto" && bpData.right !== "" && bpData.right !== undefined) ||
        (bpData.bottom !== "auto" && bpData.bottom !== "" && bpData.bottom !== undefined) ||
        (bpData.left !== "auto" && bpData.left !== "" && bpData.left !== undefined) ||
        (bpData.translateX !== 0 && bpData.translateX !== "" && bpData.translateX !== undefined) ||
        (bpData.translateY !== 0 && bpData.translateY !== "" && bpData.translateY !== undefined)
      );
      attrs[`layoutUseCustomPosition${bp.toUpperCase()}`] = hasCustomValue;
    });

    setAttributes(attrs);
  };

  const handleResponsiveToggle = (value) => {
    const newData = JSON.parse(JSON.stringify(positionData));
    const pcData = newData.pc;
    const attrs = { [responsiveAttrName]: value };
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        Object.keys(pcData).forEach((key) => {
          newData[bp][key] = pcData[key];
        });
      }
    });
    attrs[attrName] = newData;

    // is-custom-positionクラス用フラグを連動（PC値を全BPにコピーするため、全BPで同じ判定）
    const pcHasCustomValue = (
      (pcData.type && pcData.type !== "" && pcData.type !== "relative") ||
      (pcData.top !== "auto" && pcData.top !== "" && pcData.top !== undefined) ||
      (pcData.right !== "auto" && pcData.right !== "" && pcData.right !== undefined) ||
      (pcData.bottom !== "auto" && pcData.bottom !== "" && pcData.bottom !== undefined) ||
      (pcData.left !== "auto" && pcData.left !== "" && pcData.left !== undefined) ||
      (pcData.zIndex !== "auto" && pcData.zIndex !== "" && pcData.zIndex !== undefined) ||
      (pcData.translateX !== 0 && pcData.translateX !== "" && pcData.translateX !== undefined) ||
      (pcData.translateY !== 0 && pcData.translateY !== "" && pcData.translateY !== undefined)
    );
    enabledBreakpoints.forEach((bp) => {
      attrs[`layoutUseCustomPosition${bp.toUpperCase()}`] = pcHasCustomValue;
    });

    setAttributes(attrs);
  };

  const renderPositionControls = (tabName) => {
    const tabData = positionData[tabName] || getDefaultLayoutPosition().pc;
    const positionType = tabData.type || "relative";

    return (
      <div className="zenblocks-inspector-layout-position">
        <SelectControl
          label={__("Position Type", "zenblocks")}
          value={positionType}
          options={[
            { label: __("Relative", "zenblocks"), value: "relative" },
            { label: __("Absolute", "zenblocks"), value: "absolute" },
          ]}
          onChange={(value) => handleChange("type", value, tabName)}
        />

        {["top", "right", "bottom", "left"].map((direction) => {
          const currentValue = tabData[direction];
          const isAuto = currentValue === "auto" || currentValue === "" || currentValue === undefined;
          const dirLabel = direction.charAt(0).toUpperCase() + direction.slice(1);

          return (
            <div key={direction} style={{ marginBottom: "16px", paddingLeft: "6px", paddingRight: "6px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                <label style={{ fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__(dirLabel, "zenblocks")}</label>
                <ButtonGroup>
                  <Button isSmall variant={isAuto ? "primary" : "secondary"} onClick={() => handleChange(direction, "auto", tabName)}>
                    Auto
                  </Button>
                  <Button isSmall variant={!isAuto ? "primary" : "secondary"} onClick={() => handleChange(direction, 0, tabName)}>
                    Value
                  </Button>
                </ButtonGroup>
              </div>
              {!isAuto && (
                <div className="layout-position-controls">
                  <RangeControl
                    value={typeof currentValue === "number" ? currentValue : 0}
                    onChange={(value) => handleChange(direction, value, tabName)}
                    min={-1000}
                    max={1000}
                    step={1}
                    withInputField={true}
                  />
                  <SelectControl
                    value={tabData[`${direction}Unit`] || "px"}
                    options={unitOptions}
                    onChange={(value) => handleChange(`${direction}Unit`, value, tabName)}
                    __nextHasNoMarginBottom={true}
                    className="unit-select"
                  />
                </div>
              )}
            </div>
          );
        })}

        {(() => {
          const zIndexValue = tabData.zIndex;
          const isZIndexAuto = zIndexValue === "auto" || zIndexValue === "" || zIndexValue === undefined;
          return (
            <div style={{ marginBottom: "16px", paddingLeft: "6px", paddingRight: "6px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                <label style={{ fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Z-Index", "zenblocks")}</label>
                <ButtonGroup>
                  <Button isSmall variant={isZIndexAuto ? "primary" : "secondary"} onClick={() => handleChange("zIndex", "auto", tabName)}>
                    Auto
                  </Button>
                  <Button isSmall variant={!isZIndexAuto ? "primary" : "secondary"} onClick={() => handleChange("zIndex", 0, tabName)}>
                    {__("Value", "zenblocks")}
                  </Button>
                </ButtonGroup>
              </div>
              {!isZIndexAuto && (
                <NumberControl
                  value={typeof zIndexValue === "number" ? zIndexValue : 0}
                  onChange={(value) => handleChange("zIndex", value !== undefined && value !== "" ? parseInt(value, 10) : 0, tabName)}
                  min={-9999}
                  max={9999}
                  step={1}
                />
              )}
            </div>
          );
        })()}

        <h3 style={{ marginTop: "40px", marginBottom: "10px", paddingLeft: "6px", paddingRight: "6px", fontSize: "12px", fontWeight: "normal" }}>
          {__("Transform Translate", "zenblocks")}
        </h3>

        {["X", "Y"].map((axis) => {
          const key = `translate${axis}`;
          const unitKey = `translate${axis}Unit`;
          const currentValue = tabData[key];

          return (
            <div key={axis} style={{ marginBottom: "16px", paddingLeft: "6px", paddingRight: "6px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                <label style={{ fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__(`Translate ${axis}`, "zenblocks")}</label>
                <Button isSmall variant="secondary" onClick={() => handleChange(key, 0, tabName)}>
                  {__("Reset", "zenblocks")}
                </Button>
              </div>
              <div className="layout-position-controls">
                <RangeControl
                  value={currentValue !== "" && currentValue !== undefined ? currentValue : 0}
                  onChange={(value) => handleChange(key, value, tabName)}
                  min={-1000}
                  max={1000}
                  step={1}
                  withInputField={true}
                />
                <SelectControl
                  value={tabData[unitKey] || "%"}
                  options={[
                    { label: "%", value: "%" },
                    { label: "px", value: "px" },
                    { label: "vw", value: "vw" },
                    { label: "vh", value: "vh" },
                  ]}
                  onChange={(value) => handleChange(unitKey, value, tabName)}
                  __nextHasNoMarginBottom={true}
                  className="unit-select"
                />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  const content = (
    <div className="zenblocks-inspector-layout-position">
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderPositionControls(tabName)}
      </ResponsiveControlV2>
    </div>
  );

  return (
    <PanelBodyWithSync title={title || __("Position", "zenblocks")} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} level={2} panelType="settings" panelName="layout-position">
      {isPro ? <ProFeatureOverlay featureName="ポジション設定" learnMorePath={learnMorePath}>{content}</ProFeatureOverlay> : content}
      <style>
        {`
        .layout-position-controls {
          display: flex;
          align-items: flex-start;
          padding-top: 10px;
        }
        .layout-position-controls .components-range-control {
          flex: 1;
        }
        .layout-position-controls .unit-select {
          flex: 0 0 70px;
          margin-left: 8px;
        }
        `}
      </style>
    </PanelBodyWithSync>
  );
};

export default LayoutPositionSettingV7;
