import {
  AutoComplete,
  Dropdown,
  FormField,
  Input,
  MultiSelect,
  Text,
  listItemSelectBuilder
} from "@wix/design-system";
import React, { useContext, useMemo, useState } from "react";
import { EditorContext } from "./../../../../ricos-context/index.js";
import { Link_Target } from "./../../../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { useBiNext } from "./../../../bi-context-provider/bi-context-provider.js";
import { LINK_MODAL_ID } from "./../../../link-modal/constants.js";
import {
  SECTION_MULTISELECT,
  SECTION_SELECT,
  SECTION_TYPE_SELECT
} from "../../data-hooks/data-hooks.js";
import { SectionEmptyState } from "./empty-state.js";
import { useSectionOptions } from "./use-options.js";
const SectionDesktop = ({
  autoCompletePopoverProps,
  autoFocus,
  dropDownPopoverProps,
  link,
  tooltipProps,
  multipleSections,
  onSelect,
  onSubmit,
  t,
  setMultipleSections
}) => {
  const logBi = useBiNext({ pluginId: "link", modalId: LINK_MODAL_ID });
  const { sections, sectionTypeOptions } = useSectionOptions();
  const { adapter } = useContext(EditorContext);
  const enableMultipleSelection = adapter.tiptapEditor?.state?.selection?.empty && !adapter.getEditorCommands().hasLinkInSelection();
  const sectionOptions = useMemo(
    () => sections.map(
      (section) => Object.assign(
        listItemSelectBuilder({
          ellipsis: true,
          titleMaxLines: 2,
          id: section.id,
          label: section.title,
          prefix: section.prefixAvatar,
          size: "small",
          subtitle: section.subtitle,
          title: section.title,
          tooltipProps: {
            ...tooltipProps,
            children: section.title,
            enterDelay: 1e3,
            placement: "top"
          }
        }),
        {
          node: section.node,
          prefix: section.prefix
        }
      )
    ),
    [sections, tooltipProps]
  );
  const [selectedTypeOption, setSelectedTypeOption] = useState(
    sectionTypeOptions[0]
  );
  const [selectedOption, setSelectedOption] = useState(
    // Initially "all" option types are selected so any found option should be present in `filteredOptions` below:
    () => link.anchor && sectionOptions.find((option) => option.node.id === link.anchor) || null
  );
  const [searchPrefix, setSearchPrefix] = useState(selectedOption?.prefix || null);
  const [searchText, setSearchText] = useState(selectedOption?.label || "");
  const filteredOptions = useMemo(() => {
    const lowerSearchText = searchText.trim().toLowerCase();
    return sectionOptions.filter(
      (option) => (selectedTypeOption.id === "all" || option.node.type === selectedTypeOption.id) && (selectedOption || !lowerSearchText || typeof option.label === "string" && option.label?.toLowerCase().includes(lowerSearchText))
    );
  }, [sectionOptions, searchText, selectedTypeOption]);
  const onChangeInput = (value) => {
    setSearchPrefix(null);
    setSearchText(value);
    setSelectedOption(null);
  };
  const onSelectTypeOption = (option) => {
    setSelectedTypeOption(option);
    logBi({
      dataHook: SECTION_TYPE_SELECT,
      value: `${option.id}`
    });
  };
  const onSelectValueOption = (option) => {
    setSearchPrefix(option.prefix);
    setSearchText(option.label || searchText);
    setSelectedOption(option);
    onSelect(option.node.id, option.label);
    logBi({ dataHook: SECTION_SELECT, value: option.label });
  };
  const onEnterPressed = (evt) => {
    if (selectedOption) {
      onSelect(selectedOption.node.id, selectedOption.label);
      onSubmit(evt);
    }
    if (multipleSections.length > 0 && !isOptionMarked) {
      onSubmit(evt);
      setIsOptionMarked(false);
    }
  };
  if (sectionOptions.length === 0) {
    return /* @__PURE__ */ React.createElement(SectionEmptyState, { t });
  }
  const [isOptionMarked, setIsOptionMarked] = useState(false);
  const onMultiSelectOption = (option) => {
    setIsOptionMarked(false);
    setMultipleSections((prev) => [
      ...prev,
      {
        anchor: option.node.id,
        defaultName: option.label,
        target: Link_Target.BLANK,
        url: void 0
      }
    ]);
    logBi({ dataHook: SECTION_MULTISELECT, value: option.label });
  };
  const onRemoveTag = (tagId) => setMultipleSections((prevTags) => prevTags.filter((currTag) => currTag.anchor !== tagId));
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(FormField, { label: t("LinkSettings_Sections_TypeDropdown_Label"), labelPlacement: "top" }, /* @__PURE__ */ React.createElement(
    Dropdown,
    {
      dataHook: SECTION_TYPE_SELECT,
      onSelect: onSelectTypeOption,
      options: sectionTypeOptions,
      popoverProps: dropDownPopoverProps,
      selectedId: selectedTypeOption.id,
      size: "small",
      valueParser: (option) => option.label
    }
  )), /* @__PURE__ */ React.createElement(
    FormField,
    {
      label: t(
        enableMultipleSelection ? "LinkSettings_Sections_MultiSelect_Label" : "LinkSettings_Sections_AutoComplete_Label"
      ),
      labelPlacement: "top"
    },
    enableMultipleSelection ? /* @__PURE__ */ React.createElement(
      MultiSelect,
      {
        autoFocus,
        dataHook: SECTION_MULTISELECT,
        dropdownWidth: "auto",
        emptyStateMessage: /* @__PURE__ */ React.createElement(Text, { skin: "disabled", size: "small" }, searchText ? t("LinkSettings_Sections_AutoComplete_NoResults_Search", { searchText }) : t("LinkSettings_Sections_AutoComplete_NoResults_All")),
        minWidthPixels: "252px",
        onChange: (evt) => onChangeInput(evt.target.value),
        onEnterPressed,
        options: filteredOptions,
        placeholder: t("LinkSettings_Sections_MultiSelect_Placeholder"),
        popoverProps: autoCompletePopoverProps,
        prefix: searchPrefix && /* @__PURE__ */ React.createElement(Input.IconAffix, null, searchPrefix),
        size: "small",
        textOverflow: "ellipsis",
        value: searchText,
        onSelect: onMultiSelectOption,
        onRemoveTag,
        tags: multipleSections.map((section) => ({
          id: section.anchor || "",
          label: section?.defaultName || ""
        })),
        onOptionMarked: (option) => {
          if (option) {
            setIsOptionMarked(true);
          }
        }
      }
    ) : /* @__PURE__ */ React.createElement(
      AutoComplete,
      {
        autoFocus,
        dataHook: SECTION_SELECT,
        dropdownWidth: "auto",
        emptyStateMessage: /* @__PURE__ */ React.createElement(Text, { skin: "disabled", size: "small" }, searchText ? t("LinkSettings_Sections_AutoComplete_NoResults_Search", { searchText }) : t("LinkSettings_Sections_AutoComplete_NoResults_All")),
        focusOnSelectedOption: true,
        markedOption: filteredOptions.some((opt) => opt.id === selectedOption?.id) ? selectedOption?.id : void 0,
        minWidthPixels: "252px",
        onChange: (evt) => onChangeInput(evt.target.value),
        onEnterPressed,
        onSelect: onSelectValueOption,
        options: filteredOptions,
        placeholder: t("LinkSettings_Sections_AutoComplete_Placeholder"),
        popoverProps: autoCompletePopoverProps,
        prefix: searchPrefix && /* @__PURE__ */ React.createElement(Input.IconAffix, null, searchPrefix),
        selectedId: selectedOption?.id,
        size: "small",
        textOverflow: "ellipsis",
        value: searchText
      }
    )
  ));
};
export {
  SectionDesktop
};
//# sourceMappingURL=section-desktop.js.map
