'use strict';

var iconsReact = require('@cloudtower/icons-react');
var core = require('@linaria/core');
var index$1 = require('../Icon/index.js');
var index = require('../Typo/index.js');
var useParrotTranslation = require('../../hooks/useParrotTranslation.js');
var _ = require('lodash');
var React = require('react');
var index$2 = require('../../coreX/OverflowTooltip/index.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const searchInputRecentSearchLocalStorageKey = "search-input-recent-search";
const useRecentSearch = (recentSearchLocalStorageKey, maxRecentCount, setValue, onChange) => {
  const { t } = useParrotTranslation();
  const [recentSearchKeys, setRecentSearchKeys] = React.useState([]);
  React.useEffect(() => {
    if (!recentSearchLocalStorageKey)
      return;
    try {
      const currRecentSearchKeys = JSON.parse(
        localStorage.getItem(searchInputRecentSearchLocalStorageKey) || "{}"
      )[recentSearchLocalStorageKey];
      setRecentSearchKeys(currRecentSearchKeys || []);
    } catch (error) {
      setRecentSearchKeys([]);
    }
  }, [recentSearchLocalStorageKey]);
  const setRecentSearchKeysDebounceRef = React.useRef();
  React.useEffect(() => {
    if (!recentSearchLocalStorageKey)
      return;
    const fn = _.debounce((val) => {
      if (!val || !recentSearchLocalStorageKey)
        return;
      setRecentSearchKeys((preState) => {
        const newState = [...preState].filter((item) => item !== val);
        if (newState.length >= maxRecentCount)
          newState.pop();
        newState.unshift(val);
        try {
          const recentSearchMap = JSON.parse(
            localStorage.getItem(searchInputRecentSearchLocalStorageKey) || "{}"
          );
          localStorage.setItem(
            searchInputRecentSearchLocalStorageKey,
            JSON.stringify(__spreadProps(__spreadValues({}, recentSearchMap), {
              [recentSearchLocalStorageKey]: newState
            }))
          );
        } catch (err) {
          console.error(err);
        }
        return newState;
      });
    }, 400);
    setRecentSearchKeysDebounceRef.current = fn;
    return () => fn.cancel();
  }, [maxRecentCount, recentSearchLocalStorageKey]);
  const antd5DropdownMenu = React.useMemo(
    () => ({
      onClick: ({ key: val }) => {
        var _a;
        setValue(val);
        onChange == null ? void 0 : onChange(val);
        (_a = setRecentSearchKeysDebounceRef.current) == null ? void 0 : _a.call(setRecentSearchKeysDebounceRef, val);
      },
      items: [
        {
          key: "recent-search",
          className: core.cx("recent-search-menu-item", index.Typo.Label.l4_regular),
          disabled: true,
          label: /* @__PURE__ */ React__default.default.createElement("span", null, t("components.recent_search"))
        },
        ...recentSearchKeys.map((k) => ({
          key: k,
          label: /* @__PURE__ */ React__default.default.createElement(
            index$1,
            {
              src: iconsReact.Search24Icon,
              hoverSrc: iconsReact.Search24BlueIcon,
              iconHeight: 24,
              iconWidth: 24
            },
            /* @__PURE__ */ React__default.default.createElement(index$2, { content: k })
          )
        }))
      ],
      // 避免 Dropdown 点击时被 Input blur 关闭
      onMouseDown: (e) => e.preventDefault()
    }),
    [onChange, recentSearchKeys, setRecentSearchKeysDebounceRef, setValue, t]
  );
  return {
    recentSearchKeys,
    setRecentSearchKeysDebounceRef,
    antd5DropdownMenu
  };
};

exports.searchInputRecentSearchLocalStorageKey = searchInputRecentSearchLocalStorageKey;
exports.useRecentSearch = useRecentSearch;
