import {
  Box,
  FieldSet,
  FillPreview,
  FormField,
  Input,
  SegmentedToggle,
  Thumbnail
} from "@wix/design-system";
import { ButtonRoundedSmall } from "@wix/wix-ui-icons-common";
import lodash from "lodash";
import React, { useContext, useEffect, useReducer, useRef, useState } from "react";
import {
  EditorContext,
  ModalServiceContext,
  RicosContext,
  ZIndexContext
} from "./../../ricos-context/index.js";
import { ButtonData_Styles_ButtonSize } from "./../../ricos-schema/next-schema/generated/ricos_document.js";
import { toHexFormat } from "./../../ricos-styles/index.js";
import { resolveColorToDisplayHex } from "./../../_shared/resolve-color-to-display-hex.js";
import { schemaGradientToCss } from "./../../_shared/schema-gradient-to-css.js";
import { useNodeAttrs } from "./../../_shared/use-node-attrs.js";
import { ButtonColorPicker } from "./../components/button-color-picker.js";
import { buttonsModals } from "./../constants.js";
import { SWATCH_TOGGLE } from "./../../ui-components/color-picker/button-color-swatches/data-hooks.js";
import {
  ColorPickerLiveSiteColorHint,
  ColorWithOpacityInput,
  NumberInputWithLabel,
  usePanelContainerElement
} from "./../../ui-components/index.js";
import {
  DESIGN_SETTINGS_BACKGROUND_COLOR_INPUT,
  DESIGN_SETTINGS_BORDER_COLOR_INPUT,
  DESIGN_SETTINGS_BORDER_WIDTH_INPUT,
  DESIGN_SETTINGS_CORNER_RADIUS_INPUT,
  DESIGN_SETTINGS_TEXT_COLOR_INPUT
} from "../data-hooks.js";
const defaultBorderRadius = 0;
const defaultBorderWidth = 0;
const BUTTON_NORMAL_STATE_TOGGLE_VALUE = "NORMAL";
const BUTTON_HOVER_STATE_TOGGLE_VALUE = "HOVER";
const themeButtonSizeMap = {
  small: ButtonData_Styles_ButtonSize.SMALL,
  medium: ButtonData_Styles_ButtonSize.MEDIUM,
  large: ButtonData_Styles_ButtonSize.LARGE
};
const DesignComponent = ({
  config,
  onChange,
  defaultBackgroundColor,
  defaultTextColor,
  nodeId,
  nodeType,
  logBi
}) => {
  const { t, isMobile, environment, theme } = useContext(RicosContext);
  const modalService = useContext(ModalServiceContext);
  const { adapter } = useContext(EditorContext);
  const { pmNodeAttrs } = useNodeAttrs(nodeId, nodeType);
  const containerEl = usePanelContainerElement();
  const forceUpdate = useReducer((x) => x + 1, 0)[1];
  const zIndexService = useContext(ZIndexContext);
  const zIndex = zIndexService.getZIndex("DIALOG");
  const backgroundPickerToggleRef = useRef(null);
  const textPickerToggleRef = useRef(null);
  const borderPickerToggleRef = useRef(null);
  const [buttonStateToggleValue, setButtonStateToggleValue] = useState("NORMAL");
  const isHoverState = buttonStateToggleValue === BUTTON_HOVER_STATE_TOGGLE_VALUE;
  const button = nodeId ? adapter.tiptapEditor.view.dom.querySelector(`[data-hook~=button-viewer-${nodeId}`) : void 0;
  const buttonStyle = button ? window.getComputedStyle(button) : void 0;
  const styles = pmNodeAttrs?.styles;
  const textColor = styles?.textColor ?? toHexFormatSafe(buttonStyle?.getPropertyValue("color")) ?? defaultTextColor;
  const borderColor = styles?.borderColor ?? toHexFormatSafe(buttonStyle?.getPropertyValue("border-color"));
  const backgroundColor = (styles?.background?.type === "COLOR" ? styles.background.color : void 0) ?? styles?.backgroundColor ?? defaultBackgroundColor ?? toHexFormatSafe(buttonStyle?.getPropertyValue("background-color"));
  const borderWidth = styles?.borderWidth ?? parseToInt(buttonStyle?.getPropertyValue("border-width")) ?? defaultBorderWidth;
  const borderRadius = styles?.borderRadius ?? parseToInt(buttonStyle?.getPropertyValue("border-radius")) ?? defaultBorderRadius;
  const buttonSize = styles?.buttonSize ?? themeButtonSizeMap[theme?.customStyles?.button?.buttonSize] ?? ButtonData_Styles_ButtonSize.MEDIUM;
  const textColorHover = styles?.textColorHover ?? toHexFormatSafe(buttonStyle?.getPropertyValue("color")) ?? textColor;
  const borderColorHover = styles?.borderColorHover ?? toHexFormatSafe(buttonStyle?.getPropertyValue("border-color")) ?? borderColor;
  const backgroundColorHover = (styles?.backgroundHover?.type === "COLOR" ? styles.backgroundHover.color : void 0) ?? styles?.backgroundColorHover ?? toHexFormatSafe(buttonStyle?.getPropertyValue("background-color")) ?? backgroundColor;
  const backgroundGradient = styles?.background?.type === "GRADIENT" ? schemaGradientToCss(styles.background.gradient, theme.colorPalette) : void 0;
  const backgroundGradientHover = styles?.backgroundHover?.type === "GRADIENT" ? schemaGradientToCss(styles.backgroundHover.gradient, theme.colorPalette) : void 0;
  const setHoverPreview = (applyPreview) => {
    adapter.tiptapEditor.chain().setHoverPreview(applyPreview).run();
    forceUpdate();
  };
  useEffect(() => {
    setHoverPreview(isHoverState);
    return () => setHoverPreview(false);
  }, [isHoverState]);
  const handleOnChange = (newData) => {
    const newStyles = {
      ...styles,
      ...newData
    };
    onChange({
      styles: {
        ...newStyles,
        borderRadius: newStyles?.borderRadius === defaultBorderRadius ? void 0 : newStyles?.borderRadius,
        borderWidth: newStyles?.borderWidth === defaultBorderWidth ? void 0 : newStyles?.borderWidth
      }
    });
  };
  const showLiveSiteHint = environment !== "liveSite" && environment !== "wixel";
  const getDefaultColor = (colorType) => {
    if (colorType === "backgroundColor") {
      return isHoverState ? backgroundColorHover : backgroundColor;
    }
    if (colorType === "textColor") {
      return isHoverState ? textColorHover : textColor;
    }
    return isHoverState ? borderColorHover : borderColor;
  };
  const openColorPicker = (colorType) => {
    const referenceElement = getPickerToggleRef(colorType) ?? void 0;
    const modalId = buttonsModals.colorPicker;
    modalService.togglePluginPanel({
      id: modalId,
      Component: ButtonColorPicker,
      componentProps: {
        modalId,
        nodeId,
        nodeType,
        colorType,
        isHoverState,
        referenceElement,
        config,
        defaultColor: getDefaultColor(colorType),
        onValueSelected: onValueChange(colorType),
        onColorAdded: getLegacyOnColorAdded(colorType)
      },
      isMobile,
      positioning: {
        referenceElement,
        placement: "left"
      },
      type: void 0,
      onClickOutside: {
        on: "pointerup",
        handler: lodash.noop
      },
      focusReturnElement: referenceElement ?? void 0
    });
  };
  const onValueChange = (colorType) => (value) => {
    const hoverSuffix = isHoverState ? "Hover" : "";
    if (colorType === "backgroundColor") {
      const background = value ? value.gradient ? { type: "GRADIENT", gradient: value.gradient } : value.color ? { type: "COLOR", color: value.color } : void 0 : void 0;
      handleOnChange({
        [`background${hoverSuffix}`]: background
      });
    } else {
      handleOnChange({ [`${colorType}${hoverSuffix}`]: value?.color });
    }
  };
  const onColorChange = (colorType) => (color) => onValueChange(colorType)(color ? { color } : void 0);
  const getLegacyOnColorAdded = (colorType) => {
    if (colorType === "backgroundColor") {
      return config.onBackgroundColorAdded;
    } else if (colorType === "textColor") {
      return config.onTextColorAdded;
    } else {
      return config.onBorderColorAdded;
    }
  };
  const getPickerToggleRef = (colorType) => {
    if (colorType === "backgroundColor") {
      return backgroundPickerToggleRef.current;
    } else if (colorType === "textColor") {
      return textPickerToggleRef.current;
    } else {
      return borderPickerToggleRef.current;
    }
  };
  return /* @__PURE__ */ React.createElement(
    Box,
    {
      direction: "vertical",
      width: "100%",
      padding: "SP4",
      paddingTop: "SP3",
      paddingBottom: "SP3",
      gap: "SP2"
    },
    /* @__PURE__ */ React.createElement(FormField, { inputWidth: "100%" }, /* @__PURE__ */ React.createElement(
      SegmentedToggle,
      {
        defaultSelected: buttonStateToggleValue,
        size: "small",
        onClick: (_, value) => setButtonStateToggleValue(value)
      },
      /* @__PURE__ */ React.createElement(SegmentedToggle.Button, { value: BUTTON_NORMAL_STATE_TOGGLE_VALUE }, t("ButtonModal_Design_Normal_State_Toggle")),
      /* @__PURE__ */ React.createElement(SegmentedToggle.Button, { value: BUTTON_HOVER_STATE_TOGGLE_VALUE }, t("ButtonModal_Design_Hover_State_Toggle"))
    )),
    isHoverState ? null : /* @__PURE__ */ React.createElement(Box, { paddingTop: "SP1" }, /* @__PURE__ */ React.createElement(
      FormField,
      {
        label: t("ButtonModal_Button_Size"),
        labelSize: "small",
        labelPlacement: "left",
        labelWidth: "1fr",
        labelAlignment: "middle"
      },
      /* @__PURE__ */ React.createElement(Box, { direction: "horizontal", gap: "6px" }, /* @__PURE__ */ React.createElement(
        SizeOption,
        {
          selected: buttonSize === ButtonData_Styles_ButtonSize.SMALL,
          icon: /* @__PURE__ */ React.createElement(ButtonRoundedSmall, { size: 12 }),
          onClick: () => handleOnChange({ buttonSize: ButtonData_Styles_ButtonSize.SMALL })
        }
      ), /* @__PURE__ */ React.createElement(
        SizeOption,
        {
          selected: buttonSize === ButtonData_Styles_ButtonSize.MEDIUM,
          icon: /* @__PURE__ */ React.createElement(ButtonRoundedSmall, { size: 18 }),
          onClick: () => handleOnChange({ buttonSize: ButtonData_Styles_ButtonSize.MEDIUM })
        }
      ), /* @__PURE__ */ React.createElement(
        SizeOption,
        {
          selected: buttonSize === ButtonData_Styles_ButtonSize.LARGE,
          icon: /* @__PURE__ */ React.createElement(ButtonRoundedSmall, { size: 24 }),
          onClick: () => handleOnChange({ buttonSize: ButtonData_Styles_ButtonSize.LARGE })
        }
      ))
    )),
    /* @__PURE__ */ React.createElement(Box, { direction: "vertical", gap: "SP3" }, /* @__PURE__ */ React.createElement(
      ColorWithOpacityInput,
      {
        label: t("ButtonModal_Background_Color"),
        fill: (() => {
          const gradient = isHoverState ? backgroundGradientHover : backgroundGradient;
          return gradient ? { type: "gradient", gradient } : {
            type: "color",
            color: isHoverState ? backgroundColorHover : backgroundColor,
            onChange: onColorChange("backgroundColor")
          };
        })(),
        onColorPress: () => openColorPicker("backgroundColor"),
        colorPickerRef: backgroundPickerToggleRef,
        inputDataHook: DESIGN_SETTINGS_BACKGROUND_COLOR_INPUT,
        zIndex
      }
    ), showLiveSiteHint && /* @__PURE__ */ React.createElement(ColorPickerLiveSiteColorHint, null)),
    /* @__PURE__ */ React.createElement(
      FieldSet,
      {
        legend: t("ButtonModal_Text_Color"),
        legendPlacement: "left",
        columns: "auto 30px",
        alignment: "center",
        dataHook: DESIGN_SETTINGS_TEXT_COLOR_INPUT
      },
      /* @__PURE__ */ React.createElement("div", null),
      /* @__PURE__ */ React.createElement(
        FillPreview,
        {
          fill: resolveColorToDisplayHex(isHoverState ? textColorHover : textColor, containerEl),
          onClick: () => openColorPicker("textColor"),
          ref: textPickerToggleRef,
          dataHook: SWATCH_TOGGLE
        }
      )
    ),
    /* @__PURE__ */ React.createElement(
      ColorWithOpacityInput,
      {
        label: t("ButtonModal_Border_Color"),
        fill: {
          type: "color",
          color: isHoverState ? borderColorHover : borderColor,
          onChange: onColorChange("borderColor")
        },
        onColorPress: () => openColorPicker("borderColor"),
        colorPickerRef: borderPickerToggleRef,
        inputDataHook: DESIGN_SETTINGS_BORDER_COLOR_INPUT,
        zIndex
      }
    ),
    isHoverState ? null : /* @__PURE__ */ React.createElement(
      NumberInputWithLabel,
      {
        label: t("ButtonModal_Width_Input"),
        dataHook: DESIGN_SETTINGS_BORDER_WIDTH_INPUT,
        suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, t("Common_Units_PX")),
        value: borderWidth,
        min: 0,
        max: 15,
        onChange: (width) => handleOnChange({ borderWidth: width }),
        logBi,
        zIndex
      }
    ),
    isHoverState ? null : /* @__PURE__ */ React.createElement(
      NumberInputWithLabel,
      {
        label: t("ButtonModal_Radius_Input"),
        dataHook: DESIGN_SETTINGS_CORNER_RADIUS_INPUT,
        suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, t("Common_Units_PX")),
        value: borderRadius,
        min: 0,
        max: 30,
        onChange: (radius) => handleOnChange({ borderRadius: radius }),
        logBi,
        zIndex
      }
    )
  );
};
const SizeOption = ({
  icon,
  selected,
  onClick
}) => {
  return /* @__PURE__ */ React.createElement(
    Thumbnail,
    {
      height: 30,
      width: 30,
      size: "tiny",
      onClick,
      selected,
      noPadding: true,
      contentAlignment: "center"
    },
    /* @__PURE__ */ React.createElement(Box, { align: "center" }, icon)
  );
};
const toHexFormatSafe = (color) => {
  return color ? toHexFormat(color) : void 0;
};
const parseToInt = (value) => {
  if (value === void 0) {
    return void 0;
  }
  const parsedValue = parseInt(value);
  return isNaN(parsedValue) ? void 0 : parsedValue;
};
export {
  DesignComponent
};
//# sourceMappingURL=design-component.js.map
