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

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

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconFrameRadius = () => {
    if (effectiveHoverState) {
      const syncAttrs = {};
      enabledBreakpoints.forEach((bp) => {
        const bpUpper = bp.toUpperCase();
        syncAttrs[`iconFrameRadius${bpUpper}Hover`] = attributes[`iconFrameRadius${bpUpper}`];
        syncAttrs[`iconFrameRadiusUnit${bpUpper}Hover`] = attributes[`iconFrameRadiusUnit${bpUpper}`];
      });
      syncAttrs.useResponsiveIconFrameRadiusHover = attributes.useResponsiveIconFrameRadius || false;
      setAttributes(syncAttrs);
    } else if (onSync) {
      onSync();
    }
  };

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

    const syncAttrs = {};
    const pcRadius = attributes[`iconFrameRadiusPC${suffix}`];
    const pcUnit = attributes[`iconFrameRadiusUnitPC${suffix}`];
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`iconFrameRadius${bp.toUpperCase()}${suffix}`] = pcRadius;
        syncAttrs[`iconFrameRadiusUnit${bp.toUpperCase()}${suffix}`] = pcUnit;
      }
    });
    setAttributes(syncAttrs);
  };

  const renderRadiusControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const radiusValue = attributes[`iconFrameRadius${deviceSuffix}${suffix}`] ?? attributes.iconFrameRadius ?? 0;
    const unitValue = attributes[`iconFrameRadiusUnit${deviceSuffix}${suffix}`] ?? attributes.iconFrameRadiusUnit ?? "px";

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

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

    return (
      <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
        <div style={{ flex: 1 }}>
          <RangeControl value={radiusValue} onChange={handleRadiusChangeForDevice} min={0} max={999} step={1} />
        </div>
        <div style={{ minWidth: "40px" }}>
          <SelectControl
            value={unitValue}
            options={[
              { label: "px", value: "px" },
              { label: "%", value: "%" },
            ]}
            onChange={handleUnitChangeForDevice}
          />
        </div>
      </div>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __("Border Radius", "zenblocks")} 
      initialOpen={initialOpen} 
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncIconFrameRadius : undefined}
      className="zenblocks-nested-panel"
      titleClassName="zenblocks-panel-title--no-margin"
      level={3}
      panelType="settings"
      panelName="icon-frame-radius"
    >
      <div className="zenblocks-inspector-icon-frame-radius">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderRadiusControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export default IconFrameRadiusSettingV5;
