import React, { useEffect, useRef, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';

import { AutoComplete, Input, Pagination, Tabs } from 'antd';
import classNames from 'classnames';
import PinyinMatch from 'pinyin-match';

import Icon, {
  CloseOutlined,
  RightCircleOutlined,
  SearchOutlined,
} from '@ant-design/icons';

import Draggable from './draggable';
import styles from './index.less';
//
// const { TabPane } = Tabs;
const HistorySvg = () => (
  <svg
    className="icon"
    viewBox="0 0 1024 1024"
    version="1.1"
    width="10"
    height="10"
  >
    <path
      d="M1016.405333 0h-351.573333a7.594667 7.594667 0 0 0-5.376 12.885333l149.077333 149.674667-244.224 249.770667H434.346667A7.594667 7.594667 0 0 0 426.666667 419.84v169.898667c0 4.266667 3.413333 7.594667 7.594666 7.594666h169.813334c4.266667 0 7.68-3.413333 7.68-7.594666V486.826667l263.253333-257.792 136.106667 135.509333A7.594667 7.594667 0 0 0 1024 359.253333V7.68A7.594667 7.594667 0 0 0 1016.405333 0z"
      fill="#C1C1C1"
    />
    <path
      d="M979.626667 640a45.226667 45.226667 0 0 0-44.202667 46.08v249.258667H88.490667V88.576h245.418666l1.194667-0.085333A45.056 45.056 0 0 0 378.88 44.288 45.056 45.056 0 0 0 333.994667 0H7.68A7.68 7.68 0 0 0 0 7.68v1008.64c0 4.266667 3.413333 7.68 7.68 7.68h1008.64c4.266667 0 7.68-3.413333 7.68-7.68V686.08a45.226667 45.226667 0 0 0-44.373333-46.08z"
      fill="#C1C1C1"
    />
  </svg>
);
const HistoryHrefIcon = props => <Icon component={HistorySvg} {...props} />;
const Empty = () => (
  <div className={styles.empty}>
    <img
      src="https://panda-water.cn/web4/assets/images/dataNull/暂无数据大.png"
      alt=""
    />
    <p>非常抱歉，找不到和您查询相关的内容或信息</p>
  </div>
);
function itemRender(current, type, originalElement) {
  if (type === 'prev') {
    return <a>上一页</a>;
  }
  if (type === 'next') {
    return <a>下一页</a>;
  }
  return originalElement;
}
const Modal = props => {
  const dragRef = useRef(null);
  const searchRef = useRef(null);
  const [isWidgetShow, setIsWidgetShow] = useState(props.visible);
  const [keyword, setKeyWord] = useState(props.value);
  const [searchProduct, setSearchProduct] = useState([]);
  const [eventCounts, setEventCounts] = useState(() => ['resultConsole', -1]);
  // const [tabIndex]
  const [pageCurrent, setPageCurrent] = useState(1);
  const [fasts, setFasts] = useState(
    props.console.concat(props.willSearch) || [],
  );
  const [searchProductList, setSearchProductList] = useState([]);
  const recentKeywords = props.recentKeywords.toJS
    ? props.recentKeywords.toJS()
    : props.recentKeywords;
  const { triggerElRef } = props;
  // eslint-disable-next-line consistent-return,func-names
  const target = (function() {
    if (triggerElRef.current) {
      const rect = triggerElRef.current.getBoundingClientRect();
      return {
        y: rect.top,
        x: rect.left,
      };
    }
  })();

  const rawData = props.menu.concat(props.flatMenu);
  useEffect(() => {
    const ret = [];
    const searchResult = [];
    // eslint-disable-next-line array-callback-return
    props.menu.map(item => {
      const match = PinyinMatch.match(item.name, keyword);
      if (match) {
        ret.push(item);
      }
    });
    setSearchProduct(ret);
    rawData.forEach(item => {
      if (keyword !== '' && PinyinMatch.match(item.name, keyword)) {
        searchResult.push(item);
      }
    });
    setFasts(searchResult);
  }, [keyword]);

  useEffect(() => {
    setKeyWord(props.value);
  }, [props.value]);

  const onNavUp = () => {};
  const onNavDown = () => {};
  const RESULT_KEYS = ['resultConsole'];
  const getFistKey = (response, key, type) => {
    /* eslint-disable */
    const result = RESULT_KEYS.filter(item => {
      const ret = response[item];
      return !!(ret && 'success' === ret.type && ret.response.items.length > 0);
    });
    if(0 === result.length) {
      return null;
    };
    if(!key) {
      return 'down' === type ? result[0]:result[result.length - 1];
    }
    const index = result.indexOf(key);
    return index < 0 ? null: 'down' === type ? index + 1 < result.length ? result[index + 1]: null: index - 1 >= 0 ? result[index - 1]: null;

  }

  const transfromEventHander = useCallback((children, data, type) => {
    if (children === 'none') {
      return
    }

    if (null === children) {
      const key = getFistKey(data, null,  type);
      if (!key) {
        return null;
      }
      const ret = data[key];
      const currentIndex = 'up' === type ? ret.response.items.length - 1 : 0
      return 'success' !== ret.type ? null : (
        setEventCounts([key, currentIndex]),
          'up' === type ? (children[currentIndex].focus()): (children[currentIndex].focus())
      );
    }

    let eventsKey = eventCounts[0];
    let eventsIndex = eventCounts[1];
    let resultData = data[eventsKey];
    if ('success' !== resultData.type) {
      return null;
    }
    const index= "up" === type ? eventsIndex - 1: eventsIndex + 1;
    if(index >=0 && index < resultData.response.items.length) {
      return setEventCounts([eventsKey, index]), 'up' === type ? children[index].focus(): children[index].focus()
    }
    const getKey = getFistKey(data, eventsKey, type);
    if(!getKey) {
      return null;
    }
    const result = data[getKey];
    if('success' !== result.type) {
      return null;
    }
    if('up' === type) {
      return setEventCounts([getKey, result.response.items.length - 1]), children[result.response.items.length - 1].focus()
    }
    return setEventCounts([getKey, 0]), searchRef.current.children[0].focus()
  }, [eventCounts, fasts])

  const transfomResponse = (data) => {
    return {
      query: props.value,
      response: {
        items: data,
        total: data.length
      },
      type: 'success'
    }
  }
  const eventHander = useCallback(
    event => {
      // eslint-disable-next-line default-case
      const data = {
        resultConsole: transfomResponse(searchRef.current.children)
      };
      switch (event.code) {
        case 'ArrowDown':
          event.preventDefault();
          transfromEventHander(searchRef.current.children, data, 'down')
          break;
        case 'ArrowUp':
          event.preventDefault();
          transfromEventHander(searchRef.current.children, data, 'up')
          break;
      }
    },
    [fasts, eventCounts],
  );
  useEffect(() => {
    props.visible && document.addEventListener('keydown', eventHander);
    return function() {
      return document.removeEventListener('keydown', eventHander);
    };
  }, [props.visible, fasts, eventCounts]);

  useEffect(() => {
    setIsWidgetShow(props.visible);
  }, [props.visible]);
  const transformSearchHistory = () => {
    const label = keyword !== '' ? '你是不是想搜：' : '搜索历史：';
    const data = keyword !== '' ? searchProduct : recentKeywords;
    const ret = [
      {
        value: '搜索历史：',
        label: (
          <li className={styles['group-label']} title={label} tabIndex={-1}>
            <div className={styles['item-inner']}>搜索历史：</div>
          </li>
        ),
      },
    ];
    // eslint-disable-next-line array-callback-return
    data.map((item, index) => {
      ret.push({
        value: item.name || item.data,
        label: (
          <li
            className={styles['group-item']}
            title={item.data || item.name}
            dataindex={index}
          >
            <div className={styles['item-inner']}>
              <span className={styles['item-text']}>
                {item.data || item.name}
              </span>
            </div>
          </li>
        ),
      });
    });
    return ret.length > 0 ? ret : [];
  };

  const goFeature = (event, item) => {
    event.persist && event.persist();
    event && event.stopPropagation();
    props.goFeature(item.path, item, keyword);
  };
  const goProduct = (event, item) => {
    event.persist && event.persist();
    event && event.stopPropagation();
    props.goProduct && props.goProduct(event, item, keyword);
  };
  const paginationProps = {
    total: fasts.length,
    current: pageCurrent,
    pageSize: 20,
    onChange: page => {
      setPageCurrent(page);
    },
  };
  const largestPage = Math.ceil(paginationProps.total / 20);

  if (paginationProps.current > largestPage) {
    paginationProps.current = largestPage;
  }
  const paginationContent = () => {
    if (paginationProps.total < 20) {
      return null;
    }
    return (
      <div className={styles.footer}>
        <Pagination
          {...paginationProps}
          showSizeChanger={false}
          itemRender={itemRender}
          size="small"
        />
      </div>
    );
  };

  const transformSearchFasts = () => {
    if (fasts.length === 0) {
      return <Empty />;
    }
    let splitDataSource = [...fasts];
    if (
      fasts.length >
      (paginationProps.current - 1) * paginationProps.pageSize
    ) {
      splitDataSource = [...fasts].splice(
        (paginationProps.current - 1) * paginationProps.pageSize,
        paginationProps.pageSize,
      );
    }
    return (
      <div className={styles.resultContainer} ref={searchRef}>
        {splitDataSource.map((item, index) => {
          const match = props.matchValue(item.name, keyword);
          const name =
            keyword !== '' && match ? (
              <div className={styles.withHightLight}>
                {item.name.substring(0, match[0])}
                <em>{item.name.substring(match[0], match[1] + 1)}</em>
                {item.name.substring(match[1] + 1)}
              </div>
            ) : (
              item.name
            );
          return (
            <a
              className={styles.item}
              key={item.name + index}
              tabIndex="1"
              onClick={event => {
                item.parent ? goFeature(event, item) : goProduct(event, item);
              }}
              onKeyDown={event => event.key === 'Enter' && event.keyCode === 13 &&  item.parent ? goFeature(event, item) : goProduct(event, item)}
            >
              <span className={styles.title}>
                {name}
                {item.parent ? (
                  <HistoryHrefIcon className={styles.href} />
                ) : (
                  <RightCircleOutlined />
                )}
              </span>
              <span className={styles.subtitle}>
                {item.parent ? item.parent.name : '产品功能入口'}
              </span>
            </a>
          );
        })}

        {paginationContent()}
      </div>
    );
  };
  const handleChange = value => {
    setKeyWord(value);
  };
  const handleSearch = value => {
    setKeyWord(value);
  };

  const handleFocus = event => {
    event.persist && event.persist();
    event && event.nativeEvent.stopImmediatePropagation();
  };

  const onSelect = value => {
    setKeyWord(value);
  };
  const onClose = () => {
    setIsWidgetShow(false);
  };
  if (!isWidgetShow) {
    return null;
  }
  if (props.visible) {
    const children = (
      <Draggable
        dragHandleClassName={styles.header}
        default={Object.assign(
          Object.assign({}, target),
          {},
          {
            width: 420,
            height: 680,
          },
        )}
        bounds="window"
        minHeight={400}
        minWidth={360}
        enableUserSelectHack={false}
      >
        <div className={styles['base-wedget']} ref={dragRef}>
          <div className={styles.header}>
            搜索更多
            {/* eslint-disable-next-line react/button-has-type */}
            <button
              className={classNames(styles.btn, styles.close)}
              onClick={onClose}
            >
              <CloseOutlined />
            </button>
          </div>
          <div className={styles.body}>
            <div className={styles.search}>
              <AutoComplete
                options={transformSearchHistory()}
                dropdownClassName={styles.searchList}
                value={keyword}
                onSelect={onSelect}
                onSearch={handleSearch}
                onChange={handleChange}
                onFocus={handleFocus}
              >
                <Input
                  size="middle"
                  placeholder="请输入"
                  allowClear
                  suffix={<SearchOutlined className="site-form-item-icon" />}
                />
              </AutoComplete>
            </div>
            <div className={styles.result}>{transformSearchFasts()}</div>
          </div>
        </div>
      </Draggable>
    );
    return ReactDOM.createPortal(children, document.body);
  }
};

export default Modal;
