import { jsx, jsxs } from 'react/jsx-runtime';
import { useRef } from 'react';
import { useKey } from '../../hooks/useKey.js';
import { MdOutlineFilterList, MdSearch, MdClose } from 'react-icons/md';
import { useColorModeValue, InputGroup, InputLeftElement, Tooltip, Tag, Icon, Input } from '@chakra-ui/react';

const SearchField = ({
  setSearchText,
  searchText,
  placeholderText = "Search...",
  className,
  icon = "search"
}) => {
  const isEmpty = !searchText || searchText === "";
  const inputRef = useRef(null);
  const isAlreadyFocused = () => document.activeElement && (inputRef == null ? void 0 : inputRef.current) && document.activeElement !== (inputRef == null ? void 0 : inputRef.current) && document.activeElement.tagName === "INPUT";
  const reset = () => setSearchText("");
  const focus = () => !isAlreadyFocused() && (inputRef == null ? void 0 : inputRef.current) && inputRef.current.focus();
  const blur = () => (inputRef == null ? void 0 : inputRef.current) && inputRef.current.blur();
  useKey("Escape", isEmpty ? blur : reset);
  useKey("/", focus);
  const tagColorScheme = useColorModeValue("gray", "light");
  return /* @__PURE__ */ jsx("div", { className: "SearchField " + className, children: /* @__PURE__ */ jsxs(InputGroup, { minWidth: "500px", children: [
    /* @__PURE__ */ jsx(InputLeftElement, { width: "2rem" }),
    /* @__PURE__ */ jsx(
      Tooltip,
      {
        placement: "bottom",
        hasArrow: true,
        py: 1,
        label: isEmpty ? /* @__PURE__ */ jsxs("span", { children: [
          /* @__PURE__ */ jsx(Tag, { colorScheme: tagColorScheme, size: "sm", children: "/" }),
          " ",
          "to focus"
        ] }) : /* @__PURE__ */ jsxs("span", { children: [
          /* @__PURE__ */ jsx(Tag, { colorScheme: tagColorScheme, size: "sm", children: "Esc" }),
          " ",
          "to clear"
        ] }),
        children: isEmpty ? /* @__PURE__ */ jsx(InputLeftElement, { onClick: focus, children: /* @__PURE__ */ jsx(
          Icon,
          {
            "data-testid": "search-field-search-icon",
            as: icon === "filter" ? MdOutlineFilterList : MdSearch,
            color: "gray.300",
            "aria-label": "search-icon-focus"
          }
        ) }) : /* @__PURE__ */ jsx(InputLeftElement, { onClick: reset, children: /* @__PURE__ */ jsx(
          Icon,
          {
            "data-testid": "search-field-reset-icon",
            as: MdClose,
            color: "gray.300",
            "aria-label": "search-icon-reset"
          }
        ) })
      }
    ),
    /* @__PURE__ */ jsx(
      Input,
      {
        "data-testid": "search-field-input",
        ref: inputRef,
        type: "text",
        className: "search-control",
        placeholder: placeholderText,
        onChange: (event) => setSearchText(event.target.value),
        value: searchText
      }
    )
  ] }) });
};

export { SearchField as default };
//# sourceMappingURL=SearchField.js.map
