import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, ColorPalette, ButtonGroup, Button, ToggleControl } 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 getDefaultBorder = () => ({
  pc: { width: 0, style: "none", color: "transparent", boxSizing: "border-box" },
  md: { width: "", style: "", color: "", boxSizing: "" },
  tb: { width: "", style: "", color: "", boxSizing: "" },
  sp: { width: "", style: "", color: "", boxSizing: "" }
});

const StylingBorderSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? 'borderV2Hover' : 'borderV2';
  const enabledAttrName = effectiveHoverState ? 'borderEnabledHover' : 'borderEnabled';
  const responsiveAttrName = effectiveHoverState ? 'useResponsiveBorderHover' : 'useResponsiveBorder';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const borderEnabled = attributes[enabledAttrName] !== undefined ? attributes[enabledAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

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

  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) => {
    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 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", boxSizing: "border-box" };
        } else {
          newBorder[bp] = { width: "", style: "", color: "", boxSizing: "" };
        }
      });
    } else {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newBorder[bp] = { width: 0, style: "none", color: "transparent", boxSizing: "border-box" };
        } else {
          newBorder[bp] = { width: "", style: "", color: "", boxSizing: "" };
        }
      });
    }
    setAttributes({ [v2Key]: newBorder });
  };

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

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

  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 boxSizingValue = tabData.boxSizing || "border-box";

    return (
      <>
        <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>
          <ButtonGroup style={{ display: "flex", width: "100%" }}>
            {borderStyles.map((style) => (
              <Button
                key={style.value}
                variant={(tabData.style || "none") === 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={() => handleBorderChange("boxSizing", 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>
      </>
    );
  };

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="styling-border">
      <div className="zenblocks-inspector-styling-border">
        <ToggleControl
          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 getBorderValue = (attributes, device = "pc", property = "width", isHoverState = false) => {
  const v2Key = isHoverState ? 'borderV2Hover' : 'borderV2';
  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 default StylingBorderSettingV5;
