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

const getDefaultBorder = () => ({
  pc: { width: 0, style: "none", color: "transparent", colorAlpha: 1, boxSizing: "border-box" },
  md: { width: "", style: "", color: "", colorAlpha: "", boxSizing: "" },
  tb: { width: "", style: "", color: "", colorAlpha: "", boxSizing: "" },
  sp: { width: "", style: "", color: "", colorAlpha: "", boxSizing: "" }
});

const StylingBorderSettingV8 = ({ 
  attributes, 
  setAttributes, 
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  attrName = "borderV2",
  enabledAttrName: customEnabledAttrName,
  responsiveAttrName: customResponsiveAttrName,
  isHoverState = false,
  supportsHover = true,
  showBoxSizing = true,
  showEnableToggle = true,
  level = 2
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  
  const v2Key = effectiveHoverState ? `${attrName}Hover` : attrName;
  const enabledAttrName = customEnabledAttrName || (effectiveHoverState ? `${attrName.replace('V2', '')}EnabledHover` : `${attrName.replace('V2', '')}Enabled`);
  const baseAttrName = attrName.replace(/V2$/, "");
  const responsiveAttrName = customResponsiveAttrName || `useResponsive${baseAttrName.charAt(0).toUpperCase() + baseAttrName.slice(1)}${effectiveHoverState ? 'Hover' : ''}`;
  
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const borderEnabled = showEnableToggle ? (attributes[enabledAttrName] !== undefined ? attributes[enabledAttrName] : false) : true;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const borderData = attributes[v2Key] || getDefaultBorder();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncBorder = () => {
    if (effectiveHoverState) {
      const normalData = attributes[attrName] || getDefaultBorder();
      const normalEnabledKey = customEnabledAttrName
        ? customEnabledAttrName.replace(/Hover$/, '')
        : `${attrName.replace('V2', '')}Enabled`;
      const normalResponsiveKey = customResponsiveAttrName
        ? customResponsiveAttrName.replace(/Hover$/, '')
        : `useResponsive${baseAttrName.charAt(0).toUpperCase() + baseAttrName.slice(1)}`;
      const syncAttrs = {
        [`${attrName}Hover`]: JSON.parse(JSON.stringify(normalData)),
        [`${normalResponsiveKey}Hover`]: attributes[normalResponsiveKey] || false,
      };
      if (showEnableToggle) {
        syncAttrs[`${normalEnabledKey}Hover`] = attributes[normalEnabledKey] !== undefined ? attributes[normalEnabledKey] : false;
      }
      setAttributes(syncAttrs);
    } else if (onSync) {
      onSync();
    }
  };

  const handleBorderChange = (property, value) => {
    const newBorder = JSON.parse(JSON.stringify(borderData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newBorder[bp][property] = value;
      });
    } else {
      newBorder[activeTab][property] = value;
    }
    setAttributes({ [v2Key]: newBorder });
  };

  const handleColorChange = (value) => {
    handleBorderChange("color", value === undefined || value === null ? "transparent" : value);
  };

  const handleColorAlphaChange = (value) => {
    handleBorderChange("colorAlpha", value);
  };

  const handleBorderEnabledToggle = (value) => {
    setAttributes({ [enabledAttrName]: value });
    const newBorder = JSON.parse(JSON.stringify(borderData));
    if (value) {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newBorder[bp] = { width: 1, style: "solid", color: "#000000", colorAlpha: 1, boxSizing: "border-box" };
        } else {
          newBorder[bp] = { width: "", style: "", color: "", colorAlpha: "", boxSizing: "" };
        }
      });
    } else {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newBorder[bp] = { width: 0, style: "none", color: "transparent", colorAlpha: 1, boxSizing: "border-box" };
        } else {
          newBorder[bp] = { width: "", style: "", color: "", colorAlpha: "", boxSizing: "" };
        }
      });
    }
    setAttributes({ [v2Key]: newBorder });
  };

  const handleResponsiveToggle = (value) => {
    const newBorder = JSON.parse(JSON.stringify(borderData));
    const pcData = newBorder.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newBorder[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newBorder, [responsiveAttrName]: value });
  };

  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 boxSizingOptions = [
    { label: "Border Box", value: "border-box" },
    { label: "Content Box", value: "content-box" },
  ];

  const renderBorderControls = (tabName) => {
    const tabData = borderData[tabName] || getDefaultBorder().pc;
    const colorValue = tabData.color;
    const colorAlphaValue = tabData.colorAlpha !== "" && tabData.colorAlpha !== undefined ? tabData.colorAlpha : 1;
    const boxSizingValue = tabData.boxSizing || "border-box";

    return (
      <>
        <CustomColorPalette
          color={colorValue}
          alpha={colorAlphaValue}
          enableGradient={false}
          enableAlpha={true}
          onColorChange={handleColorChange}
          onAlphaChange={handleColorAlphaChange}
          label={__("Color", "zenblocks")}
        />

        <RangeControl
          label={__("Width", "zenblocks")}
          value={tabData.width === "" ? 0 : tabData.width}
          onChange={(value) => handleBorderChange("width", value)}
          min={0}
          max={100}
          step={1}
          className="zenblocks-inspector-styling-border__width-control"
        />
        <div className="zenblocks-inspector-styling-border__style-select" style={{ marginBottom: "16px" }}>
          <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Style", "zenblocks")}</label>
          <div className="border-side-button-group" style={{ display: "flex", gap: "4px" }}>
            {borderStyles.map((style) => (
              <button
                key={style.value}
                type="button"
                className={`border-side-button${(tabData.style || "none") === style.value ? " is-checked" : ""}`}
                onClick={() => handleBorderChange("style", style.value)}
                title={style.label}
              >
                <BorderStyleIcon type={style.icon} />
              </button>
            ))}
          </div>
        </div>
        {showBoxSizing && !effectiveHoverState && (
          <div className="zenblocks-inspector-styling-border__box-sizing" style={{ marginBottom: "16px" }}>
            <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Box Sizing", "zenblocks")}</label>
            <ButtonGroup style={{ display: "flex", width: "100%" }}>
              {boxSizingOptions.map((option) => (
                <Button
                  key={option.value}
                  variant={boxSizingValue === option.value ? "primary" : "secondary"}
                  onClick={() => handleBorderChange("boxSizing", option.value)}
                  style={{
                    flex: 1,
                    justifyContent: "center",
                    padding: "4px 8px",
                    minHeight: "32px",
                    height: "32px",
                    fontSize: "11px",
                  }}
                >
                  {option.label}
                </Button>
              ))}
            </ButtonGroup>
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={effectiveHoverState ? handleSyncBorder : undefined} className="zenblocks-nested-panel" level={level} panelType="settings" panelName="styling-border">
      <div className="zenblocks-inspector-styling-border">
        {showEnableToggle && (
          <StyledToggle
            label={__("Border", "zenblocks")}
            checked={borderEnabled}
            onChange={handleBorderEnabledToggle}
          />
        )}
        {borderEnabled && (
          <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderBorderControls(tabName)}
        </ResponsiveControlV2>
        )}
      </div>
    </PanelBodyWithSync>
  );
};

export const getBorderValueV8 = (attributes, attrName = "borderV2", device = "pc", property = "width", isHoverState = false) => {
  const v2Key = isHoverState ? `${attrName}Hover` : attrName;
  const borderData = attributes[v2Key];
  if (!borderData) return property === "width" ? "0" : "";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = borderData[bp];
    if (bpData) {
      const value = bpData[property];
      if (value !== "" && value !== undefined && value !== null) {
        return value;
      }
    }
  }

  return property === "width" ? "0" : "";
};

export const getDirectBorderValueV8 = (attributes, attrName = "borderV2", device = "pc", property = "width", isHoverState = false) => {
  const v2Key = isHoverState ? `${attrName}Hover` : attrName;
  const borderData = attributes[v2Key];
  
  if (!borderData || !borderData[device]) return undefined;
  
  const value = borderData[device][property];
  
  if (value !== "" && value !== undefined && value !== null) {
    return value;
  }
  
  return undefined;
};

export default StylingBorderSettingV8;
