import React from "react";
import { __ } from "@wordpress/i18n";
import { PanelBody, RangeControl, ColorPalette, ButtonGroup, Button } from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

const StylingBorderSettingV3 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const responsiveEnabled = attributes.responsiveStylingBorder !== undefined ? attributes.responsiveStylingBorder : false;
  const { activeTab } = useResponsiveTab();

  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) {
      setAttributes({
        [`stylingBorder${property}PC`]: value,
        [`stylingBorder${property}SP`]: value,
      });
    } else {
      const attributeName = `stylingBorder${property}${activeTab.toUpperCase()}`;
      setAttributes({ [attributeName]: value });
    }
  };

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

  const handleResponsiveToggle = (value) => {
    setAttributes({ responsiveStylingBorder: value });

    if (!value) {
      setAttributes({
        stylingBorderWidthSP: attributes.stylingBorderWidthPC,
        stylingBorderStyleSP: attributes.stylingBorderStylePC,
        stylingBorderColorSP: attributes.stylingBorderColorPC,
        stylingBoxSizingSP: attributes.stylingBoxSizingPC,
      });
    }
  };

  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) {
      setAttributes({
        stylingBoxSizingPC: value,
        stylingBoxSizingSP: value,
      });
    } else {
      const attributeName = `stylingBoxSizing${tabName.toUpperCase()}`;
      setAttributes({ [attributeName]: value });
    }
  };

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

    return (
      <div className="zenblocks-inspector-styling-border">
        <RangeControl
          label={__("Width", "zenblocks")}
          value={attributes[`stylingBorderWidth${tabName.toUpperCase()}`]}
          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${tabName.toUpperCase()}`] === 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>
        <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 (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveStylingBorder"
      >
        {(tabName) => renderBorderControls(tabName)}
      </ResponsiveControl>
    </PanelBody>
  );
};

export default StylingBorderSettingV3;
