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

  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 = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`iconFrameBorderWidth${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameBorderWidthPC${suffix}`];
      syncAttrs[`iconFrameBorderWidthUnit${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameBorderWidthUnitPC${suffix}`];
      syncAttrs[`iconFrameBorderStyle${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameBorderStylePC${suffix}`];
      syncAttrs[`iconFrameBorderColor${bp.toUpperCase()}${suffix}`] = attributes[`iconFrameBorderColorPC${suffix}`];
    });
    setAttributes(syncAttrs);
  };

  const renderBorderSidesControl = () => {
    const sidesAttr = `iconFrameBorderSides${suffix}`;
    const sides = attributes[sidesAttr] || attributes.iconFrameBorderSides || ["top", "right", "bottom", "left"];
    
    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 = sides.includes(side);
            return (
              <button
                key={side}
                type="button"
                className={`border-side-button ${isChecked ? "is-checked" : ""}`}
                onClick={() => {
                  const currentSides = attributes[sidesAttr] || attributes.iconFrameBorderSides || ["top", "right", "bottom", "left"];
                  const newSides = isChecked ? currentSides.filter((s) => s !== side) : [...currentSides, side];
                  setAttributes({ [sidesAttr]: newSides });
                }}
              >
                {side === "top" ? "T" : side === "right" ? "R" : side === "bottom" ? "B" : "L"}
              </button>
            );
          })}
        </div>
      </div>
    );
  };

  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 handleWidthChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`iconFrameBorderWidth${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`iconFrameBorderWidth${deviceSuffix}${suffix}`]: value });
      }
    };

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

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

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

    return (
      <>
        <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}
            onColorChange={handleColorChangeForDevice}
          />
        </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} 
      onSync={onSync} 
      className="zenblocks-nested-panel"
    >
      {renderBorderSidesControl()}
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderBorderControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default IconFrameBorderSettingV6;
