import React from "react";
import { __ } from "@wordpress/i18n";
import { PanelBody, SelectControl, ToggleControl, RangeControl, TextControl, ButtonGroup, Button } from "@wordpress/components";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

const LayoutPositionSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

  // Set layoutUseCustomPosition to true by default for both PC and SP
  React.useEffect(() => {
    if (!attributes.layoutUseCustomPositionPC) {
      setAttributes({ layoutUseCustomPositionPC: true });
    }
    if (!attributes.layoutUseCustomPositionSP) {
      setAttributes({ layoutUseCustomPositionSP: true });
    }
  }, []);

  const handlePositionTypeChange = (value) => {
    setAttributes({ [`layoutPositionType${activeTab.toUpperCase()}`]: value });
  };

  const handleCustomPositionChange = (direction, value) => {
    setAttributes({ [`layoutCustomPosition${direction}${activeTab.toUpperCase()}`]: value });
  };

  const handleIndividualPositionUnitChange = (direction, value) => {
    setAttributes({ [`layoutCustomPosition${direction}Unit${activeTab.toUpperCase()}`]: value });
  };

  const handleIndividualTranslateUnitChange = (axis, value) => {
    setAttributes({ [`layoutTransformTranslate${axis}Unit${activeTab.toUpperCase()}`]: value });
  };

  const handleTransformTranslateChange = (axis, value) => {
    setAttributes({ [`layoutTransformTranslate${axis}${activeTab.toUpperCase()}`]: value });
  };

  const handleTransformTranslateReset = (axis) => {
    setAttributes({ [`layoutTransformTranslate${axis}${activeTab.toUpperCase()}`]: 0 });
  };

  const renderPositionControls = (tabName) => {
    const positionType = attributes[`layoutPositionType${tabName.toUpperCase()}`] || "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}${tabName.toUpperCase()}`];
          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} ${tabName.toUpperCase()}`, "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${tabName.toUpperCase()}`] || "px"}
                    options={[
                      { label: "px", value: "px" },
                      { label: "%", value: "%" },
                      { label: "vw", value: "vw" },
                      { label: "vh", value: "vh" },
                    ]}
                    onChange={(value) => handleIndividualPositionUnitChange(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}${tabName.toUpperCase()}`];

          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} ${tabName.toUpperCase()}`, "zenblocks")}
                </label>
                <Button 
                  isSmall 
                  variant="secondary"
                  onClick={() => handleTransformTranslateReset(axis)}
                >
                  {__("Reset", "zenblocks")}
                </Button>
              </div>
              <div className="layout-position-controls">
                <RangeControl
                  value={currentValue || 0}
                  onChange={(value) => handleTransformTranslateChange(axis, value)}
                  min={-200}
                  max={200}
                  step={1}
                  withInputField={true}
                />
                <SelectControl
                  value={attributes[`layoutTransformTranslate${axis}Unit${tabName.toUpperCase()}`] || "%"}
                  options={[
                    { label: "%", value: "%" },
                    { label: "px", value: "px" },
                    { label: "vw", value: "vw" },
                    { label: "vh", value: "vh" },
                  ]}
                  onChange={(value) => handleIndividualTranslateUnitChange(axis, value)}
                  __nextHasNoMarginBottom={true}
                  className="unit-select"
                />
              </div>
            </div>
          );
        })}
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{(tabName) => renderPositionControls(tabName)}</ResponsiveControl>
      <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>
    </PanelBody>
  );
};

export default LayoutPositionSetting;
