import * as React from 'react';
import { Input, Popover } from 'antd';
import { Empty } from '@/lib';
import { useEffect, useRef, useState } from 'react';
import { AudioOutlined, SearchOutlined } from '@ant-design/icons';
import { useClickAway, useDebounce } from 'ahooks';
import _ from 'lodash';
import classNames from 'classnames';
import { history } from 'umi';
import { MenuDataItem } from '../../typings';
import styles from './index.less';
import { observer } from 'mobx-react';
import { baseLayoutStore } from '@/layouts/BaseLayout/Store';

declare type ComponentProps = {
  originalMenu: MenuDataItem[];
  onMenuSelect: Function;
};

const Search = observer(({ originalMenu, onMenuSelect }: ComponentProps) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [value, setValue] = useState();
  const debouncedValue = useDebounce(value, { wait: 1000 });
  const logoRef = useRef(null);
  useClickAway(
    () => {
      setVisible(false);
    },
    () => logoRef.current,
  );

  const iconColor = baseLayoutStore.layout === 'side' ? '#666' : 'rgba(255,255,255,.2)'
  const bgColor = baseLayoutStore.layout === 'side' ? 'rgba(0,0,0,.1)' : 'rgba(255,255,255,.2)'

  return (
    <Popover
      visible={visible}
      title={null}
      content={
        <Menu
          searchKey={debouncedValue}
          originalMenu={originalMenu}
          onMenuSelect={onMenuSelect}
        />
      }
      placement="bottom"
      trigger="click"
      overlayClassName={styles.overlay}
      overlayInnerStyle={{ borderRadius: 8 }}
    >
      <div
        className={styles.search}
        ref={logoRef}
        onClick={() => setVisible(!visible)}
      >
        <Input
          size="small"
          placeholder="搜索你想要的功能"
          style={{
            width: '100%',
            outline: 'none',
            borderRadius: 4,
            background: bgColor,
            border: 'none',
            height: 30,
            lineHeight: '30px',
          }}
          prefix={
            <SearchOutlined style={{ color: iconColor }} />
          }
          suffix={
            <AudioOutlined
              style={{
                fontSize: 16,
                color: iconColor,
              }}
            />
          }
          allowClear
          onChange={(e: any) => setValue(e.target.value)}
        />
      </div>
    </Popover>
  );
})

declare type MenuProps = {
  searchKey: string | undefined;
  originalMenu: MenuDataItem[];
  onMenuSelect: Function;
};
const Menu: React.FC<MenuProps> = ({
  originalMenu,
  searchKey,
  onMenuSelect,
}) => {
  const [data, setData] = useState<any[]>([]);
  useEffect(() => {
    if (!_.isEmpty(searchKey) && !_.isEmpty(originalMenu)) {
      setData(
        _.filter(
          originalMenu,
          (menu: any) =>
            menu.name.indexOf(searchKey) >= 0 ||
            menu.path.indexOf(searchKey) >= 0,
        ),
      );
    }
  }, [searchKey, originalMenu]);

  if (_.isEmpty(searchKey) || _.isEmpty(data)) {
    return (
      <div className={classNames(styles.menu, styles.empty)}>
        <Empty />
      </div>
    );
  }

  return (
    <div className={styles.menu}>
      <div className={styles.title}>功能</div>
      {_.map(data, (menu: any) => {
        if (_.isEmpty(menu.name)) {
          return null;
        }
        const index = menu.name.indexOf(searchKey);
        const name = (
          <span>
            {menu.name.substr(0, index)}
            <span style={{ color: '#0a60ff' }}>{searchKey}</span>
            <span>{menu.name.substr(index + searchKey?.length)}</span>
          </span>
        );
        return (
          <div
            key={menu.id}
            className={styles.menuItem}
            onClick={() => {
              onMenuSelect({ key: menu.id, keyPath: [menu.pid] });
              history.push(menu.path);
            }}
          >
            {name}
          </div>
        );
      })}
    </div>
  );
};

export default Search;
