import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, ColorPalette, ButtonGroup, Button } from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const StylingBorderSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? 'Hover' : '';
  const responsiveAttrName = effectiveHoverState ? 'responsiveStylingBorderHover' : 'responsiveStylingBorder';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const themeColors = useSelect((select) => {
    const settings = select(blockEditorStore).getSettings();
    return settings.colors || [];
  }, []);

  const customColors = [
    { name: __("Transparent", "zenblocks"), color: "transparent" },
    { name: __("Black", "zenblocks"), color: "#000000" },
    { name: __("White", "zenblocks"), color: "#ffffff" },
    ...themeColors.map((color) => ({
      name: color.name,
      color: color.color,
    })),
  ];

  const handleBorderChange = (property, value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`stylingBorder${property}${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attributeName = `stylingBorder${property}${deviceSuffix}${hoverSuffix}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleColorChange = (value) => {
    if (value === undefined || value === null) {
      handleBorderChange("Color", "transparent");
    } else {
      handleBorderChange("Color", value);
    }
  };

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

    if (!value) {
      const syncAttrs = {};
      enabledBreakpoints.slice(1).forEach(bp => {
        syncAttrs[`stylingBorderWidth${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingBorderWidthPC${hoverSuffix}`];
        syncAttrs[`stylingBorderStyle${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingBorderStylePC${hoverSuffix}`];
        syncAttrs[`stylingBorderColor${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingBorderColorPC${hoverSuffix}`];
      });
      if (!effectiveHoverState) {
        enabledBreakpoints.slice(1).forEach(bp => {
          syncAttrs[`stylingBoxSizing${bp.toUpperCase()}`] = attributes.stylingBoxSizingPC;
        });
      }
      setAttributes(syncAttrs);
    }
  };

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

  const renderBorderControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const colorValue = attributes[`stylingBorderColor${deviceSuffix}${hoverSuffix}`];
    const boxSizingValue = attributes[`stylingBoxSizing${deviceSuffix}`] || "border-box";

    return (
      <div className="zenblocks-inspector-styling-border">
        <RangeControl
          label={__("Width", "zenblocks")}
          value={attributes[`stylingBorderWidth${deviceSuffix}${hoverSuffix}`]}
          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-buttons" 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={attributes[`stylingBorderStyle${deviceSuffix}${hoverSuffix}`] === style.value ? "primary" : "secondary"}
                onClick={() => handleBorderChange("Style", style.value)}
                style={{
                  flex: 1,
                  justifyContent: "center",
                  padding: "4px",
                  minHeight: "32px",
                  height: "32px",
                }}
                title={style.label}
              >
                <BorderStyleIcon type={style.icon} />
              </Button>
            ))}
          </ButtonGroup>
        </div>
        {!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={() => handleBoxSizingChangeForTab(tabName, option.value)}
                  style={{
                    flex: 1,
                    justifyContent: "center",
                    padding: "4px 8px",
                    minHeight: "32px",
                    height: "32px",
                    fontSize: "11px",
                  }}
                >
                  {option.label}
                </Button>
              ))}
            </ButtonGroup>
          </div>
        )}
        <div className="zenblocks-inspector-styling-border__color-control" style={{ marginBottom: "10px" }}>
          <label style={{ display: "block", marginBottom: "8px", fontSize: "12px", fontWeight: "normal" }}>{__("Color", "zenblocks")}</label>
          <ColorPalette colors={customColors} value={colorValue === "transparent" ? undefined : colorValue} onChange={handleColorChange} disableCustomColors={false} clearable={true} />
          {colorValue === "transparent" && (
            <div
              style={{
                marginTop: "8px",
                padding: "8px",
                backgroundColor: "#f0f0f0",
                borderRadius: "4px",
                fontSize: "12px",
                color: "#666",
              }}
            >
              {__("Current setting: Transparent", "zenblocks")}
            </div>
          )}
        </div>
      </div>
    );
  };

  const boxSizingOptions = [
    { label: "Border Box", value: "border-box" },
    { label: "Content Box", value: "content-box" },
  ];

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderBorderControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default StylingBorderSettingV6;
