import { __ } from "@wordpress/i18n";
import { RangeControl, SelectControl, ButtonGroup, Button } from "@wordpress/components";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import FontColorSetting from "../font/FontColorSetting";
import PanelBodyWithSync from "../../PanelBodyWithSync";

const IconFrameBorderSettingV4 = ({ attributes, setAttributes, title, initialOpen = false, panelState, onTogglePanel, isHoverState = false, onSync }) => {
  const { activeTab } = useResponsiveTab();
  const suffix = isHoverState ? "Hover" : "";

  const responsiveAttrName = isHoverState ? "useResponsiveIconFrameBorderHover" : "useResponsiveIconFrameBorder";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  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 });

    if (!value) {
      const pcWidth = attributes[`iconFrameBorderWidthPC${suffix}`] || attributes[`iconFrameBorderWidth${suffix}`] || attributes.iconFrameBorderWidth || 1;
      const pcUnit = attributes[`iconFrameBorderWidthUnitPC${suffix}`] || attributes[`iconFrameBorderWidthUnit${suffix}`] || attributes.iconFrameBorderWidthUnit || "px";
      const pcStyle = attributes[`iconFrameBorderStylePC${suffix}`] || attributes[`iconFrameBorderStyle${suffix}`] || attributes.iconFrameBorderStyle || "solid";
      setAttributes({
        [`iconFrameBorderWidthSP${suffix}`]: pcWidth,
        [`iconFrameBorderWidthUnitSP${suffix}`]: pcUnit,
        [`iconFrameBorderStyleSP${suffix}`]: pcStyle,
      });
    }
  };

  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 handleWidthChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameBorderWidthPC${suffix}`]: value,
          [`iconFrameBorderWidthSP${suffix}`]: value,
          ...(isHoverState ? {} : { iconFrameBorderWidth: value }),
        });
      } else {
        const attributeName = `iconFrameBorderWidth${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: value });
      }
    };

    const handleUnitChangeForDevice = (unit) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameBorderWidthUnitPC${suffix}`]: unit,
          [`iconFrameBorderWidthUnitSP${suffix}`]: unit,
          ...(isHoverState ? {} : { iconFrameBorderWidthUnit: unit }),
        });
      } else {
        const attributeName = `iconFrameBorderWidthUnit${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: unit });
      }
    };

    const handleStyleChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        setAttributes({
          [`iconFrameBorderStylePC${suffix}`]: value,
          [`iconFrameBorderStyleSP${suffix}`]: value,
          ...(isHoverState ? {} : { iconFrameBorderStyle: value }),
        });
      } else {
        const attributeName = `iconFrameBorderStyle${deviceSuffix}${suffix}`;
        setAttributes({ [attributeName]: 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 sidesAttr = `iconFrameBorderSides${suffix}`;
              const sides = attributes[sidesAttr] || attributes.iconFrameBorderSides || ["top", "right", "bottom", "left"];
              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>

        <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={attributes[`iconFrameBorderColor${suffix}`] || attributes.iconFrameBorderColor}
            onColorChange={(value) => setAttributes({ [`iconFrameBorderColor${suffix}`]: value })}
          />
        </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 || panelState} onToggle={onTogglePanel} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControl enableResponsiveToggle={true} onResponsiveToggle={handleResponsiveToggle} responsiveEnabled={responsiveEnabled}>
        {(tabName) => renderBorderControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

export default IconFrameBorderSettingV4;
