import React from "react";
import { __ } from "@wordpress/i18n";
import { SelectControl, RangeControl, ButtonGroup, Button } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const LayoutPositionSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isPro = false }) => {
  const responsiveAttrName = "responsiveLayoutPosition";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  React.useEffect(() => {
    const updates = {};
    enabledBreakpoints.forEach((bp) => {
      if (!attributes[`layoutUseCustomPosition${bp.toUpperCase()}`]) {
        updates[`layoutUseCustomPosition${bp.toUpperCase()}`] = true;
      }
    });
    if (Object.keys(updates).length > 0) {
      setAttributes(updates);
    }
  }, []);

  const handlePositionTypeChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutPositionType${bp.toUpperCase()}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutPositionType${deviceSuffix}`]: value });
    }
  };

  const handleCustomPositionChange = (direction, value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutCustomPosition${direction}${bp.toUpperCase()}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutCustomPosition${direction}${deviceSuffix}`]: value });
    }
  };

  const handlePositionUnitChange = (direction, value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutCustomPosition${direction}Unit${bp.toUpperCase()}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutCustomPosition${direction}Unit${deviceSuffix}`]: value });
    }
  };

  const handleTransformChange = (axis, value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutTransformTranslate${axis}${bp.toUpperCase()}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutTransformTranslate${axis}${deviceSuffix}`]: value });
    }
  };

  const handleTransformUnitChange = (axis, value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutTransformTranslate${axis}Unit${bp.toUpperCase()}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutTransformTranslate${axis}Unit${deviceSuffix}`]: value });
    }
  };

  const handleTransformReset = (axis) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`layoutTransformTranslate${axis}${bp.toUpperCase()}`] = 0;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutTransformTranslate${axis}${deviceSuffix}`]: 0 });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

    const syncAttrs = {};
    enabledBreakpoints.forEach((bp) => {
      if (bp !== "pc") {
        syncAttrs[`layoutPositionType${bp.toUpperCase()}`] = attributes.layoutPositionTypePC;
        syncAttrs[`layoutUseCustomPosition${bp.toUpperCase()}`] = attributes.layoutUseCustomPositionPC;
      }
    });
    ["Top", "Right", "Bottom", "Left"].forEach((dir) => {
      enabledBreakpoints.forEach((bp) => {
        if (bp !== "pc") {
          syncAttrs[`layoutCustomPosition${dir}${bp.toUpperCase()}`] = attributes[`layoutCustomPosition${dir}PC`];
          syncAttrs[`layoutCustomPosition${dir}Unit${bp.toUpperCase()}`] = attributes[`layoutCustomPosition${dir}UnitPC`];
        }
      });
    });
    ["X", "Y"].forEach((axis) => {
      enabledBreakpoints.forEach((bp) => {
        if (bp !== "pc") {
          syncAttrs[`layoutTransformTranslate${axis}${bp.toUpperCase()}`] = attributes[`layoutTransformTranslate${axis}PC`];
          syncAttrs[`layoutTransformTranslate${axis}Unit${bp.toUpperCase()}`] = attributes[`layoutTransformTranslate${axis}UnitPC`];
        }
      });
    });
    setAttributes(syncAttrs);
  };

  const renderPositionControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const positionType = attributes[`layoutPositionType${deviceSuffix}`] || "relative";

    return (
      <>
        <SelectControl
          label={__("Position Type", "zenblocks")}
          value={positionType}
          options={[
            { label: __("Relative", "zenblocks"), value: "relative" },
            { label: __("Absolute", "zenblocks"), value: "absolute" },
          ]}
          onChange={handlePositionTypeChange}
        />
        {["Top", "Right", "Bottom", "Left"].map((direction) => {
          const currentValue = attributes[`layoutCustomPosition${direction}${deviceSuffix}`];
          const isAuto = currentValue === "auto" || currentValue === undefined || currentValue === null;

          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" }}>{__(`${direction}`, "zenblocks")}</label>
                <ButtonGroup>
                  <Button isSmall variant={isAuto ? "primary" : "secondary"} onClick={() => handleCustomPositionChange(direction, "auto")}>
                    Auto
                  </Button>
                  <Button isSmall variant={!isAuto ? "primary" : "secondary"} onClick={() => handleCustomPositionChange(direction, 0)}>
                    Value
                  </Button>
                </ButtonGroup>
              </div>
              {!isAuto && (
                <div className="layout-position-controls">
                  <RangeControl
                    value={typeof currentValue === "number" ? currentValue : 0}
                    onChange={(value) => handleCustomPositionChange(direction, value)}
                    min={-200}
                    max={200}
                    step={1}
                    withInputField={true}
                  />
                  <SelectControl
                    value={attributes[`layoutCustomPosition${direction}Unit${deviceSuffix}`] || "px"}
                    options={[
                      { label: "px", value: "px" },
                      { label: "%", value: "%" },
                      { label: "vw", value: "vw" },
                      { label: "vh", value: "vh" },
                    ]}
                    onChange={(value) => handlePositionUnitChange(direction, value)}
                    __nextHasNoMarginBottom={true}
                    className="unit-select"
                  />
                </div>
              )}
            </div>
          );
        })}
        <h3 style={{ marginTop: "40px", marginBottom: "10px", paddingLeft: "6px", paddingRight: "6px", fontSize: "12px", fontWeight: "normal" }}>
          {__("Transform Translate", "zenblocks")}
        </h3>

        {["X", "Y"].map((axis) => {
          const currentValue = attributes[`layoutTransformTranslate${axis}${deviceSuffix}`];

          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={() => handleTransformReset(axis)}>
                  {__("Reset", "zenblocks")}
                </Button>
              </div>
              <div className="layout-position-controls">
                <RangeControl value={currentValue || 0} onChange={(value) => handleTransformChange(axis, value)} min={-200} max={200} step={1} withInputField={true} />
                <SelectControl
                  value={attributes[`layoutTransformTranslate${axis}Unit${deviceSuffix}`] || "%"}
                  options={[
                    { label: "%", value: "%" },
                    { label: "px", value: "px" },
                    { label: "vw", value: "vw" },
                    { label: "vh", value: "vh" },
                  ]}
                  onChange={(value) => handleTransformUnitChange(axis, value)}
                  __nextHasNoMarginBottom={true}
                  className="unit-select"
                />
              </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} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="layout-position">
      {isPro ? <ProFeatureOverlay featureName="ポジション設定">{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 LayoutPositionSettingV5;
