import { __ } from "@wordpress/i18n";
import { ToggleControl, RangeControl, SelectControl } from "@wordpress/components";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import PanelBodyWithSync from "../../PanelBodyWithSync";

const IconFrameSizeSettingV4 = ({ attributes, setAttributes, title, initialOpen = false, panelState, onTogglePanel, isHoverState = false, onSync }) => {
  const { activeTab } = useResponsiveTab();
  const suffix = isHoverState ? "Hover" : "";

  const responsiveAttrName = isHoverState ? "useResponsiveIconFrameSizeHover" : "useResponsiveIconFrameSize";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  const useIndividualSize = attributes[`iconFrameUseIndividualSize${suffix}`] || false;

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

    if (!value) {
      if (useIndividualSize) {
        const pcWidth = attributes[`iconFrameWidthPC${suffix}`] || attributes[`iconFrameWidth${suffix}`] || attributes.iconFrameWidth || 0;
        const pcWidthUnit = attributes[`iconFrameWidthUnitPC${suffix}`] || attributes[`iconFrameWidthUnit${suffix}`] || attributes.iconFrameWidthUnit || "px";
        const pcHeight = attributes[`iconFrameHeightPC${suffix}`] || attributes[`iconFrameHeight${suffix}`] || attributes.iconFrameHeight || 0;
        const pcHeightUnit = attributes[`iconFrameHeightUnitPC${suffix}`] || attributes[`iconFrameHeightUnit${suffix}`] || attributes.iconFrameHeightUnit || "px";
        setAttributes({
          [`iconFrameWidthSP${suffix}`]: pcWidth,
          [`iconFrameWidthUnitSP${suffix}`]: pcWidthUnit,
          [`iconFrameHeightSP${suffix}`]: pcHeight,
          [`iconFrameHeightUnitSP${suffix}`]: pcHeightUnit,
        });
      } else {
        const pcSize = attributes[`iconFrameSizePC${suffix}`] || attributes[`iconFrameSize${suffix}`] || attributes.iconFrameSize || 0;
        const pcUnit = attributes[`iconFrameSizeUnitPC${suffix}`] || attributes[`iconFrameSizeUnit${suffix}`] || attributes.iconFrameSizeUnit || "px";
        setAttributes({
          [`iconFrameSizeSP${suffix}`]: pcSize,
          [`iconFrameSizeUnitSP${suffix}`]: pcUnit,
        });
      }
    }
  };

  const renderSizeControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    
    const sizeValue = attributes[`iconFrameSize${deviceSuffix}${suffix}`] || attributes[`iconFrameSize${suffix}`] || attributes.iconFrameSize || 0;
    const sizeUnit = attributes[`iconFrameSizeUnit${deviceSuffix}${suffix}`] || attributes[`iconFrameSizeUnit${suffix}`] || attributes.iconFrameSizeUnit || "px";
    const widthValue = attributes[`iconFrameWidth${deviceSuffix}${suffix}`] || attributes[`iconFrameWidth${suffix}`] || attributes.iconFrameWidth || 0;
    const widthUnit = attributes[`iconFrameWidthUnit${deviceSuffix}${suffix}`] || attributes[`iconFrameWidthUnit${suffix}`] || attributes.iconFrameWidthUnit || "px";
    const heightValue = attributes[`iconFrameHeight${deviceSuffix}${suffix}`] || attributes[`iconFrameHeight${suffix}`] || attributes.iconFrameHeight || 0;
    const heightUnit = attributes[`iconFrameHeightUnit${deviceSuffix}${suffix}`] || attributes[`iconFrameHeightUnit${suffix}`] || attributes.iconFrameHeightUnit || "px";

    const handleSizeChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameSizePC${suffix}`]: value,
          [`iconFrameSizeSP${suffix}`]: value,
          ...(isHoverState ? {} : { iconFrameSize: value }),
        });
      } else {
        const attributeName = `iconFrameSize${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: value });
      }
    };

    const handleSizeUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameSizeUnitPC${suffix}`]: unit,
          [`iconFrameSizeUnitSP${suffix}`]: unit,
          ...(isHoverState ? {} : { iconFrameSizeUnit: unit }),
        });
      } else {
        const attributeName = `iconFrameSizeUnit${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: unit });
      }
    };

    const handleWidthChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameWidthPC${suffix}`]: value,
          [`iconFrameWidthSP${suffix}`]: value,
          ...(isHoverState ? {} : { iconFrameWidth: value }),
        });
      } else {
        const attributeName = `iconFrameWidth${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: value });
      }
    };

    const handleWidthUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameWidthUnitPC${suffix}`]: unit,
          [`iconFrameWidthUnitSP${suffix}`]: unit,
          ...(isHoverState ? {} : { iconFrameWidthUnit: unit }),
        });
      } else {
        const attributeName = `iconFrameWidthUnit${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: unit });
      }
    };

    const handleHeightChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameHeightPC${suffix}`]: value,
          [`iconFrameHeightSP${suffix}`]: value,
          ...(isHoverState ? {} : { iconFrameHeight: value }),
        });
      } else {
        const attributeName = `iconFrameHeight${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: value });
      }
    };

    const handleHeightUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameHeightUnitPC${suffix}`]: unit,
          [`iconFrameHeightUnitSP${suffix}`]: unit,
          ...(isHoverState ? {} : { iconFrameHeightUnit: unit }),
        });
      } else {
        const attributeName = `iconFrameHeightUnit${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: unit });
      }
    };

    return (
      <>
        <ToggleControl
          label={__("Set Width and Height Individually", "zenblocks")}
          checked={useIndividualSize}
          onChange={(value) => setAttributes({ [`iconFrameUseIndividualSize${suffix}`]: value })}
        />
        {!useIndividualSize && (
          <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
            <div style={{ flex: 1 }}>
              <RangeControl value={sizeValue} onChange={handleSizeChangeForDevice} min={0} max={999} step={1} />
            </div>
            <div style={{ minWidth: "40px" }}>
              <SelectControl
                value={sizeUnit}
                options={[
                  { label: "px", value: "px" },
                  { label: "%", value: "%" },
                  { label: "em", value: "em" },
                  { label: "rem", value: "rem" },
                ]}
                onChange={handleSizeUnitChangeForDevice}
              />
            </div>
          </div>
        )}
        {useIndividualSize && (
          <>
            <div style={{ marginTop: "12px" }}>
              <label style={{ display: "block", marginBottom: "4px", fontSize: "12px" }}>{__("Width", "zenblocks")}</label>
              <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
                <div style={{ flex: 1 }}>
                  <RangeControl value={widthValue} onChange={handleWidthChangeForDevice} min={0} max={999} step={1} />
                </div>
                <div style={{ minWidth: "40px" }}>
                  <SelectControl
                    value={widthUnit}
                    options={[
                      { label: "px", value: "px" },
                      { label: "%", value: "%" },
                      { label: "em", value: "em" },
                      { label: "rem", value: "rem" },
                    ]}
                    onChange={handleWidthUnitChangeForDevice}
                  />
                </div>
              </div>
            </div>
            <div style={{ marginTop: "12px" }}>
              <label style={{ display: "block", marginBottom: "4px", fontSize: "12px" }}>{__("Height", "zenblocks")}</label>
              <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
                <div style={{ flex: 1 }}>
                  <RangeControl value={heightValue} onChange={handleHeightChangeForDevice} min={0} max={999} step={1} />
                </div>
                <div style={{ minWidth: "40px" }}>
                  <SelectControl
                    value={heightUnit}
                    options={[
                      { label: "px", value: "px" },
                      { label: "%", value: "%" },
                      { label: "em", value: "em" },
                      { label: "rem", value: "rem" },
                    ]}
                    onChange={handleHeightUnitChangeForDevice}
                  />
                </div>
              </div>
            </div>
          </>
        )}
      </>
    );
  };

  return (
    <PanelBodyWithSync title={title || __("Size", "zenblocks")} initialOpen={initialOpen || panelState} onToggle={onTogglePanel} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControl enableResponsiveToggle={true} onResponsiveToggle={handleResponsiveToggle} responsiveEnabled={responsiveEnabled}>
        {(tabName) => renderSizeControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

export default IconFrameSizeSettingV4;
