import { __ } from "@wordpress/i18n";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultIconPosition = () => ({
  pc: { gap: "", gapUnit: "px", offsetX: 45, offsetXUnit: "%", offsetY: "", offsetYUnit: "px", originX: "center", originY: "center" },
  md: { gap: "", gapUnit: "", offsetX: "", offsetXUnit: "", offsetY: "", offsetYUnit: "", originX: "", originY: "" },
  tb: { gap: "", gapUnit: "", offsetX: "", offsetXUnit: "", offsetY: "", offsetYUnit: "", originX: "", originY: "" },
  sp: { gap: "", gapUnit: "", offsetX: "", offsetXUnit: "", offsetY: "", offsetYUnit: "", originX: "", originY: "" }
});

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

const IconPositionSettingV5 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? "iconPositionV2Hover" : "iconPositionV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveIconPositionHover" : "useResponsiveIconPosition";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const iconPositionData = attributes[v2Key] || getDefaultIconPosition();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconPosition = () => {
    if (effectiveHoverState) {
      const normalData = attributes.iconPositionV2 || getDefaultIconPosition();
      const normalResponsive = attributes.useResponsiveIconPosition || false;
      setAttributes({
        iconPositionV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveIconPositionHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleChange = (changes) => {
    const newData = { ...iconPositionData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newData[bp] = { ...newData[bp], ...changes };
      });
    } else {
      newData[activeTab] = { ...newData[activeTab], ...changes };
    }
    setAttributes({ [v2Key]: newData });
  };

  const handleResponsiveToggle = (value) => {
    const newData = JSON.parse(JSON.stringify(iconPositionData));
    const pcData = newData.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newData[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newData, [responsiveAttrName]: value });
  };

  const renderPositionControls = (tabName) => {
    const tabData = iconPositionData[tabName] || { offsetX: "", offsetXUnit: "px", offsetY: "", offsetYUnit: "px", originX: "center", originY: "center" };
    const offsetX = tabData.offsetX !== "" && tabData.offsetX !== undefined ? tabData.offsetX : 0;
    const offsetXUnit = tabData.offsetXUnit || "%";
    const offsetY = tabData.offsetY !== "" && tabData.offsetY !== undefined ? tabData.offsetY : 0;
    const offsetYUnit = tabData.offsetYUnit || "%";
    const originX = tabData.originX || "center";
    const originY = tabData.originY || "center";

    // Icons for position buttons
    const IconLeft = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="4" y1="4" x2="4" y2="20" stroke="currentColor" strokeWidth="2" />
        <rect x="8" y="8" width="12" height="8" fill="currentColor" />
      </svg>
    );
    const IconCenterH = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="12" y1="4" x2="12" y2="20" stroke="currentColor" strokeWidth="2" />
        <rect x="6" y="8" width="12" height="8" fill="currentColor" />
      </svg>
    );
    const IconRight = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="20" y1="4" x2="20" y2="20" stroke="currentColor" strokeWidth="2" />
        <rect x="4" y="8" width="12" height="8" fill="currentColor" />
      </svg>
    );
    const IconTop = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="4" y1="4" x2="20" y2="4" stroke="currentColor" strokeWidth="2" />
        <rect x="8" y="8" width="8" height="12" fill="currentColor" />
      </svg>
    );
    const IconCenterV = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="4" y1="12" x2="20" y2="12" stroke="currentColor" strokeWidth="2" />
        <rect x="8" y="6" width="8" height="12" fill="currentColor" />
      </svg>
    );
    const IconBottom = ({ isActive }) => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className={isActive ? "icon-active" : "icon-inactive"}>
        <line x1="4" y1="20" x2="20" y2="20" stroke="currentColor" strokeWidth="2" />
        <rect x="8" y="4" width="8" height="12" fill="currentColor" />
      </svg>
    );

    return (
      <>
        <div className="zenblocks-position-control">
          <div className="zenblocks-position-control__label">{__("X Position", "zenblocks")}</div>
          <div className="zenblocks-position-control__row">
            <div className={`zenblocks-origin-buttons${isHoverState ? " is-disabled" : ""}`} title={isHoverState ? __("Cannot change origin on hover", "zenblocks") : undefined}>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--first ${originX === "left" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originX: "left" })}
                title={__("Left", "zenblocks")}
                disabled={isHoverState}
              >
                <IconLeft isActive={originX === "left"} />
              </button>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--middle ${originX === "center" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originX: "center" })}
                title={__("Center", "zenblocks")}
                disabled={isHoverState}
              >
                <IconCenterH isActive={originX === "center"} />
              </button>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--last ${originX === "right" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originX: "right" })}
                title={__("Right", "zenblocks")}
                disabled={isHoverState}
              >
                <IconRight isActive={originX === "right"} />
              </button>
            </div>
            <div className="zenblocks-position-control__input">
              <UnitControl
                value={`${offsetX}${offsetXUnit}`}
                onChange={(value) => {
                  const numValue = parseFloat(value);
                  const unit = value.replace(/[\d.-]/g, "");
                  const changes = {};
                  if (!isNaN(numValue)) changes.offsetX = numValue;
                  if (unit) changes.offsetXUnit = unit;
                  if (Object.keys(changes).length > 0) handleChange(changes);
                }}
                units={units}
              />
            </div>
          </div>
        </div>
        <div className="zenblocks-position-control">
          <div className="zenblocks-position-control__label">{__("Y Position", "zenblocks")}</div>
          <div className="zenblocks-position-control__row">
            <div className={`zenblocks-origin-buttons${isHoverState ? " is-disabled" : ""}`} title={isHoverState ? __("Cannot change origin on hover", "zenblocks") : undefined}>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--first ${originY === "top" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originY: "top" })}
                title={__("Top", "zenblocks")}
                disabled={isHoverState}
              >
                <IconTop isActive={originY === "top"} />
              </button>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--middle ${originY === "center" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originY: "center" })}
                title={__("Center", "zenblocks")}
                disabled={isHoverState}
              >
                <IconCenterV isActive={originY === "center"} />
              </button>
              <button
                type="button"
                className={`zenblocks-origin-button zenblocks-origin-button--last ${originY === "bottom" ? "is-active" : ""}`}
                onClick={() => !isHoverState && handleChange({ originY: "bottom" })}
                title={__("Bottom", "zenblocks")}
                disabled={isHoverState}
              >
                <IconBottom isActive={originY === "bottom"} />
              </button>
            </div>
            <div className="zenblocks-position-control__input">
              <UnitControl
                value={`${offsetY}${offsetYUnit}`}
                onChange={(value) => {
                  const numValue = parseFloat(value);
                  const unit = value.replace(/[\d.-]/g, "");
                  const changes = {};
                  if (!isNaN(numValue)) changes.offsetY = numValue;
                  if (unit) changes.offsetYUnit = unit;
                  if (Object.keys(changes).length > 0) handleChange(changes);
                }}
                units={units}
              />
            </div>
          </div>
        </div>
      </>
    );
  };

  return (
    <PanelBodyWithSync
      title={title || __("Icon Position", "zenblocks")}
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncIconPosition : undefined}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="icon-position"
    >
      <div className="zenblocks-inspector-icon-position">
        <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderPositionControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export const getIconOffsetXValue = (attributes, device = "pc", isHoverState = false) => {
  if (!attributes) return "";

  const v2Key = isHoverState ? "iconPositionV2Hover" : "iconPositionV2";
  const data = attributes[v2Key];

  if (data && data[device]) {
    const { offsetX, offsetXUnit } = data[device];
    if (offsetX !== undefined && offsetX !== null && offsetX !== "") {
      return `${offsetX}${offsetXUnit || "px"}`;
    }
  }

  return "";
};

export const getIconOffsetYValue = (attributes, device = "pc", isHoverState = false) => {
  if (!attributes) return "";

  const v2Key = isHoverState ? "iconPositionV2Hover" : "iconPositionV2";
  const data = attributes[v2Key];

  if (data && data[device]) {
    const { offsetY, offsetYUnit } = data[device];
    if (offsetY !== undefined && offsetY !== null && offsetY !== "") {
      return `${offsetY}${offsetYUnit || "px"}`;
    }
  }

  return "";
};

export const getDirectIconOffsetX = (attributes, device = "pc", isHoverState = false) => {
  const value = getIconOffsetXValue(attributes, device, isHoverState);
  return value || undefined;
};

export const getDirectIconOffsetY = (attributes, device = "pc", isHoverState = false) => {
  const value = getIconOffsetYValue(attributes, device, isHoverState);
  return value || undefined;
};

export default IconPositionSettingV5;
