import { __ } from "@wordpress/i18n";
import { ToggleControl, RangeControl, SelectControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const IconFrameSizeSettingV6 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  onSync,
  isHoverState = false, 
  supportsHover = true 
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const suffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "responsiveIconFrameSizeHover" : "responsiveIconFrameSize";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

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

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

    if (useIndividualSize) {
      const syncAttrs = {};
      enabledBreakpoints.slice(1).forEach(bp => {
        syncAttrs[`iconFrameWidth${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameWidthPC${suffix}`];
        syncAttrs[`iconFrameWidthUnit${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameWidthUnitPC${suffix}`];
        syncAttrs[`iconFrameHeight${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameHeightPC${suffix}`];
        syncAttrs[`iconFrameHeightUnit${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameHeightUnitPC${suffix}`];
      });
      setAttributes(syncAttrs);
    } else {
      const syncAttrs = {};
      enabledBreakpoints.slice(1).forEach(bp => {
        syncAttrs[`iconFrameSize${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameSizePC${suffix}`];
        syncAttrs[`iconFrameSizeUnit${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameSizeUnitPC${suffix}`];
      });
      setAttributes(syncAttrs);
    }
  };

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

    const handleSizeChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameSize${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameSize${deviceSuffix}${suffix}`]: value });
      }
    };

    const handleSizeUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameSizeUnit${bp.toUpperCase()}${suffix}`] = unit;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameSizeUnit${deviceSuffix}${suffix}`]: unit });
      }
    };

    const handleWidthChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameWidth${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameWidth${deviceSuffix}${suffix}`]: value });
      }
    };

    const handleWidthUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameWidthUnit${bp.toUpperCase()}${suffix}`] = unit;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameWidthUnit${deviceSuffix}${suffix}`]: unit });
      }
    };

    const handleHeightChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameHeight${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameHeight${deviceSuffix}${suffix}`]: value });
      }
    };

    const handleHeightUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameHeightUnit${bp.toUpperCase()}${suffix}`] = unit;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameHeightUnit${deviceSuffix}${suffix}`]: 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} 
      onSync={onSync} 
      className="zenblocks-nested-panel"
    >
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderSizeControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default IconFrameSizeSettingV6;
