import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'bisheng/router';
import {FormattedMessage} from 'react-intl';
import classNames from 'classnames';
import {Select, Menu, Row, Col, Icon, Popover, Input, Button, AutoComplete} from 'antd';
import * as utils from '../utils';
import {version as dplVersion} from '../../../../package.json';

const {Option} = Select;
const searchEngine = 'Google';
const searchLink = 'https://www.google.com/#q=site:dpl.envisioncn+';

const LOGO_MAP = {
  dark: '/images/dpllogo_dark.svg',
  green: '/images/dpllogo_green.svg',
  default: '/images/dpllogo_light.svg'
};
export default class Header extends React.Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
    intl: PropTypes.object.isRequired,
    isMobile: PropTypes.bool.isRequired,
    theme: PropTypes.string.isRequired
  };

  state = {
    menuVisible: false
  };

  componentDidMount() {
    const {intl, router} = this.context;
    router.listen(this.handleHideMenu);
    const {searchInput} = this;
    document.addEventListener('keyup', (event) => {
      if (event.keyCode === 83 && event.target === document.body) {
        searchInput.focus();
      }
    });
  }

  handleSearch = (value) => {
    if (value === searchEngine) {
      window.location.href = `${searchLink}${this.state.inputValue}`;
      return;
    }

    const {location} = this.props;
    const {intl, router} = this.context;
    this.setState({
      inputValue: ''
    }, () => {
      router.push({
        pathname: utils.getLocalizedPathname(`${value}/`, intl.locale === 'zh-CN'),
        query: location.query
      });
      this.searchInput.blur();
    });
  }

  handleInputChange = (value) => {
    this.setState({
      inputValue: value
    });
  }

  handleSelectFilter = (value, option) => {
    const optionValue = option.label.props['data-label'];
    return optionValue === searchEngine
      || optionValue.indexOf(value.toLowerCase()) > -1;
  }

  handleShowMenu = () => {
    this.setState({
      menuVisible: true
    });
  };

  handleHideMenu = () => {
    this.setState({
      menuVisible: false
    });
  };

  onMenuVisibleChange = (visible) => {
    this.setState({
      menuVisible: visible
    });
  };

  handleVersionChange = (url) => {
    const currentUrl = window.location.href;
    window.location.href = currentUrl
      .replace(window.location.origin, url);
  };

  handleLangChange = () => {
    const {
      location: {pathname}
    } = this.props;
    const currentProtocol = `${window.location.protocol}//`;
    const currentHref = window.location.href.substr(currentProtocol.length);

    if (utils.isLocalStorageNameSupported()) {
      localStorage.setItem('locale', utils.isZhCN(pathname) ? 'en-US' : 'zh-CN');
    }

    window.location.href = currentProtocol
      + currentHref.replace(
        window.location.pathname,
        utils.getLocalizedPathname(pathname, !utils.isZhCN(pathname))
      );
  };

  render() {
    const {menuVisible, inputValue} = this.state;
    const {isMobile} = this.context;
    const menuMode = isMobile ? 'inline' : 'horizontal';
    const {location, themeConfig, picked, theme} = this.props;
    const docVersions = {[dplVersion]: dplVersion, ...themeConfig.docVersions};
    const versionOptions = Object.keys(docVersions).map(version => (
      <Option value={docVersions[version]} key={version}>
        {version}
      </Option>
    ));
    const module = location.pathname
      .replace(/(^\/|\/$)/g, '')
      .split('/')
      .slice(0, -1)
      .join('/');
    let activeMenuItem = module || 'home';
    if (activeMenuItem === 'components' || location.pathname === 'changelog') {
      activeMenuItem = 'docs/react';
    }
    const {
      intl: {locale}
    } = this.context;
    const isZhCN = locale === 'zh-CN';

    const {components} = picked;
    const excludedSuffix = isZhCN ? 'en-US.md' : 'zh-CN.md';

    const renderOption = (meta) => {
      const pathSnippet = meta.filename.split('/')[1];
      const optionUrl = `/components/${pathSnippet}`;
      const {subtitle} = meta;
      return {
        value: optionUrl,
        label: (
          <div value={optionUrl} key={optionUrl} data-label={`${meta.title?.toLowerCase?.()} ${subtitle || ''}`}>
            <strong>{meta.title}</strong>
            {subtitle && <span className='ant-component-decs'>{subtitle}</span>}
          </div>
        )
      };
    };

    const options = components
      .filter(({meta}) => !meta.filename.endsWith(excludedSuffix))
      .map(({meta}) => renderOption(meta));

    const headerClassName = classNames({
      clearfix: true
    });

    const menu = [
      <Button
        size='small'
        onClick={this.handleLangChange}
        className='header-lang-button'
        key='lang-button'
      >
        <FormattedMessage id='app.header.lang' />
      </Button>,
      <span key='version' className='version'>
        <Select
          key='version'
          size='small'
          defaultValue={dplVersion}
          onChange={this.handleVersionChange}
          getPopupContainer={trigger => trigger.parentNode}
        >
          {versionOptions}
        </Select>
      </span>,
      <Menu
        className='menu-site'
        mode={menuMode}
        selectedKeys={[activeMenuItem]}
        id='nav'
        key='nav'
      >
        <Menu.Item key='docs/spec'>
          <Link to={utils.getLocalizedPathname('/docs/spec/structure', isZhCN)}>
            <FormattedMessage id='app.header.menu.spec' />
          </Link>
        </Menu.Item>
        <Menu.Item key='docs/react'>
          <Link to={utils.getLocalizedPathname('/docs/react/introduce', isZhCN)}>
            <FormattedMessage id='app.header.menu.components' />
          </Link>
        </Menu.Item>
      </Menu>
    ];

    const searchPlaceholder = locale === 'zh-CN' ? '在 DPL 中搜索' : 'Search in DPL';
    return (
      <header id='header' className={headerClassName}>
        {isMobile && (
          <Popover
            overlayClassName='popover-menu'
            placement='bottomRight'
            content={menu}
            trigger='click'
            visible={menuVisible}
            arrowPointAtCenter
            onVisibleChange={this.onMenuVisibleChange}
          >
            <Icon className='nav-phone-icon' type='menu' onClick={this.handleShowMenu} />
          </Popover>
        )}
        <Row>
          <Col xxl={4} xl={5} lg={5} md={5} sm={24} xs={24}>
            <Link to={utils.getLocalizedPathname('/', isZhCN)} id='logo'>
              <img alt='logo' src={LOGO_MAP[theme] || LOGO_MAP.default} />
            </Link>
          </Col>
          <Col xxl={20} xl={19} lg={19} md={19} sm={0} xs={0}>
            <div id='search-box'>
              <AutoComplete
                options={options}
                value={inputValue}
                dropdownClassName='component-select'
                placeholder={searchPlaceholder}
                optionLabelProp='data-label'
                filterOption={this.handleSelectFilter}
                onSelect={this.handleSearch}
                onSearch={this.handleInputChange}
                getPopupContainer={trigger => trigger.parentNode}
              >
                <Input ref={(ref) => { this.searchInput = ref; }} />
              </AutoComplete>
            </div>
            {!isMobile && menu}
          </Col>
        </Row>
      </header>
    );
  }
}
