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 IconFrameSizeSettingV5 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened,
  onToggle,
  onSync,
  isHoverState = false, 
  supportsHover = true 
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const suffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveIconFrameSizeHover" : "useResponsiveIconFrameSize";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

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

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconFrameSize = () => {
    if (effectiveHoverState) {
      const syncAttrs = {};
      enabledBreakpoints.forEach((bp) => {
        const bpUpper = bp.toUpperCase();
        syncAttrs[`iconFrameSize${bpUpper}Hover`] = attributes[`iconFrameSize${bpUpper}`];
        syncAttrs[`iconFrameSizeUnit${bpUpper}Hover`] = attributes[`iconFrameSizeUnit${bpUpper}`];
        syncAttrs[`iconFrameWidth${bpUpper}Hover`] = attributes[`iconFrameWidth${bpUpper}`];
        syncAttrs[`iconFrameWidthUnit${bpUpper}Hover`] = attributes[`iconFrameWidthUnit${bpUpper}`];
        syncAttrs[`iconFrameHeight${bpUpper}Hover`] = attributes[`iconFrameHeight${bpUpper}`];
        syncAttrs[`iconFrameHeightUnit${bpUpper}Hover`] = attributes[`iconFrameHeightUnit${bpUpper}`];
      });
      syncAttrs.iconFrameUseIndividualSizeHover = attributes.iconFrameUseIndividualSize || false;
      syncAttrs.useResponsiveIconFrameSizeHover = attributes.useResponsiveIconFrameSize || false;
      setAttributes(syncAttrs);
    } else if (onSync) {
      onSync();
    }
  };

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

    const syncAttrs = {};
    if (useIndividualSize) {
      const pcWidth = attributes[`iconFrameWidthPC${suffix}`];
      const pcWidthUnit = attributes[`iconFrameWidthUnitPC${suffix}`];
      const pcHeight = attributes[`iconFrameHeightPC${suffix}`];
      const pcHeightUnit = attributes[`iconFrameHeightUnitPC${suffix}`];
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          syncAttrs[`iconFrameWidth${bp.toUpperCase()}${suffix}`] = pcWidth;
          syncAttrs[`iconFrameWidthUnit${bp.toUpperCase()}${suffix}`] = pcWidthUnit;
          syncAttrs[`iconFrameHeight${bp.toUpperCase()}${suffix}`] = pcHeight;
          syncAttrs[`iconFrameHeightUnit${bp.toUpperCase()}${suffix}`] = pcHeightUnit;
        }
      });
    } else {
      const pcSize = attributes[`iconFrameSizePC${suffix}`];
      const pcSizeUnit = attributes[`iconFrameSizeUnitPC${suffix}`];
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          syncAttrs[`iconFrameSize${bp.toUpperCase()}${suffix}`] = pcSize;
          syncAttrs[`iconFrameSizeUnit${bp.toUpperCase()}${suffix}`] = pcSizeUnit;
        }
      });
    }
    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 updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameSize${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(updates);
      } else {
        setAttributes({ [`iconFrameSize${deviceSuffix}${suffix}`]: value });
      }
    };

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

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

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

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

    const handleHeightUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameHeightUnit${bp.toUpperCase()}${suffix}`] = unit;
        });
        setAttributes(updates);
      } 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} 
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncIconFrameSize : undefined}
      className="zenblocks-nested-panel"
      titleClassName="zenblocks-panel-title--no-margin"
      level={3}
      panelType="settings"
      panelName="icon-frame-size"
    >
      <div className="zenblocks-inspector-icon-frame-size">
        <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderSizeControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export default IconFrameSizeSettingV5;
