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

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

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconFrameBorder = () => {
    if (effectiveHoverState) {
      const syncAttrs = {};
      enabledBreakpoints.forEach((bp) => {
        const bpUpper = bp.toUpperCase();
        syncAttrs[`iconFrameBorderWidth${bpUpper}Hover`] = attributes[`iconFrameBorderWidth${bpUpper}`];
        syncAttrs[`iconFrameBorderWidthUnit${bpUpper}Hover`] = attributes[`iconFrameBorderWidthUnit${bpUpper}`];
        syncAttrs[`iconFrameBorderStyle${bpUpper}Hover`] = attributes[`iconFrameBorderStyle${bpUpper}`];
        syncAttrs[`iconFrameBorderColor${bpUpper}Hover`] = attributes[`iconFrameBorderColor${bpUpper}`];
        syncAttrs[`iconFrameBorderColorAlpha${bpUpper}Hover`] = attributes[`iconFrameBorderColorAlpha${bpUpper}`];
        syncAttrs[`iconFrameBorderSides${bpUpper}Hover`] = attributes[`iconFrameBorderSides${bpUpper}`];
      });
      syncAttrs.useResponsiveIconFrameBorderHover = attributes.useResponsiveIconFrameBorder || false;
      setAttributes(syncAttrs);
    } else if (onSync) {
      onSync();
    }
  };

  const borderStyles = [
    { label: "None", value: "none", icon: null },
    { label: "Solid", value: "solid", icon: "solid" },
    { label: "Dashed", value: "dashed", icon: "dashed" },
    { label: "Dotted", value: "dotted", icon: "dotted" },
  ];

  const BorderStyleIcon = ({ type }) => {
    const iconStyle = {
      width: "32px",
      height: "16px",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
    };

    if (type === null) {
      return (
        <span style={{ ...iconStyle, fontSize: "10px", fontWeight: "600" }}>
          NONE
        </span>
      );
    }

    if (type === "solid") {
      return (
        <span style={iconStyle}>
          <svg width="32" height="16" viewBox="0 0 32 16">
            <line x1="0" y1="8" x2="32" y2="8" stroke="currentColor" strokeWidth="3" />
          </svg>
        </span>
      );
    }

    if (type === "dashed") {
      return (
        <span style={iconStyle}>
          <svg width="32" height="16" viewBox="0 0 32 16">
            <line x1="1" y1="8" x2="31" y2="8" stroke="currentColor" strokeWidth="3" strokeDasharray="5 3" />
          </svg>
        </span>
      );
    }

    if (type === "dotted") {
      return (
        <span style={iconStyle}>
          <svg width="32" height="16" viewBox="0 0 32 16">
            <line x1="2" y1="8" x2="30" y2="8" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeDasharray="0.1 6" />
          </svg>
        </span>
      );
    }

    return null;
  };

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

    const syncAttrs = {};
    const pcWidth = attributes[`iconFrameBorderWidthPC${suffix}`];
    const pcWidthUnit = attributes[`iconFrameBorderWidthUnitPC${suffix}`];
    const pcStyle = attributes[`iconFrameBorderStylePC${suffix}`];
    const pcColor = attributes[`iconFrameBorderColorPC${suffix}`];
    const pcAlpha = attributes[`iconFrameBorderColorAlphaPC${suffix}`];
    const pcSides = attributes[`iconFrameBorderSidesPC${suffix}`] || ["top", "right", "bottom", "left"];
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`iconFrameBorderWidth${bp.toUpperCase()}${suffix}`] = pcWidth;
        syncAttrs[`iconFrameBorderWidthUnit${bp.toUpperCase()}${suffix}`] = pcWidthUnit;
        syncAttrs[`iconFrameBorderStyle${bp.toUpperCase()}${suffix}`] = pcStyle;
        syncAttrs[`iconFrameBorderColor${bp.toUpperCase()}${suffix}`] = pcColor;
        syncAttrs[`iconFrameBorderColorAlpha${bp.toUpperCase()}${suffix}`] = pcAlpha;
        syncAttrs[`iconFrameBorderSides${bp.toUpperCase()}${suffix}`] = pcSides;
      }
    });
    setAttributes(syncAttrs);
  };

  const renderBorderControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const widthValue = attributes[`iconFrameBorderWidth${deviceSuffix}${suffix}`] ?? attributes[`iconFrameBorderWidth${suffix}`] ?? attributes.iconFrameBorderWidth ?? 1;
    const unitValue = attributes[`iconFrameBorderWidthUnit${deviceSuffix}${suffix}`] || attributes[`iconFrameBorderWidthUnit${suffix}`] || attributes.iconFrameBorderWidthUnit || "px";
    const styleValue = attributes[`iconFrameBorderStyle${deviceSuffix}${suffix}`] || attributes[`iconFrameBorderStyle${suffix}`] || attributes.iconFrameBorderStyle || "solid";
    const colorValue = attributes[`iconFrameBorderColor${deviceSuffix}${suffix}`] || attributes[`iconFrameBorderColor${suffix}`] || attributes.iconFrameBorderColor || "";
    const alphaValue = attributes[`iconFrameBorderColorAlpha${deviceSuffix}${suffix}`] ?? attributes[`iconFrameBorderColorAlpha${suffix}`] ?? attributes.iconFrameBorderColorAlpha ?? 1;
    const sidesValue = attributes[`iconFrameBorderSides${deviceSuffix}${suffix}`] || attributes[`iconFrameBorderSides${suffix}`] || attributes.iconFrameBorderSides || ["top", "right", "bottom", "left"];

    const handleSidesChangeForDevice = (side) => {
      const currentSides = sidesValue;
      const isChecked = currentSides.includes(side);
      const newSides = isChecked ? currentSides.filter((s) => s !== side) : [...currentSides, side];

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

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

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

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

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

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

    return (
      <>
        <div style={{ marginBottom: "16px" }}>
          <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Display Position", "zenblocks")}</label>
          <div className="border-side-button-group" style={{ display: "flex", gap: "4px" }}>
            {["top", "right", "bottom", "left"].map((side) => {
              const isChecked = sidesValue.includes(side);
              return (
                <button
                  key={side}
                  type="button"
                  className={`border-side-button ${isChecked ? "is-checked" : ""}`}
                  onClick={() => handleSidesChangeForDevice(side)}
                >
                  {side === "top" ? "T" : side === "right" ? "R" : side === "bottom" ? "B" : "L"}
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ marginBottom: "16px" }}>
          <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Style", "zenblocks")}</label>
          <ButtonGroup style={{ display: "flex", width: "100%" }}>
            {borderStyles.map((style) => (
              <Button
                key={style.value}
                variant={styleValue === style.value ? "primary" : "secondary"}
                onClick={() => handleStyleChangeForDevice(style.value)}
                style={{
                  flex: 1,
                  justifyContent: "center",
                  padding: "4px",
                  minHeight: "32px",
                  height: "32px",
                }}
                title={style.label}
              >
                <BorderStyleIcon type={style.icon} />
              </Button>
            ))}
          </ButtonGroup>
        </div>

        <div style={{ marginBottom: "16px" }}>
          <FontColorSetting
            label={__("Color", "zenblocks")}
            colorValue={colorValue}
            alphaValue={alphaValue}
            onColorChange={handleColorChangeForDevice}
            onAlphaChange={handleAlphaChangeForDevice}
            enableAlpha={true}
          />
        </div>

        <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
          <div style={{ flex: 1 }}>
            <RangeControl label={__("Size", "zenblocks")} value={widthValue} onChange={handleWidthChangeForDevice} min={0} max={50} step={1} />
          </div>
          <div style={{ minWidth: "40px" }}>
            <SelectControl value={unitValue} options={[{ label: "px", value: "px" }]} onChange={handleUnitChangeForDevice} />
          </div>
        </div>
      </>
    );
  };

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

export default IconFrameBorderSettingV5;
