import React from 'react';
import ReactDOM from 'react-dom';
import AntdTabs from 'antd/es/tabs';
import { isFlexSupported } from 'antd/es/_util/styleChecker';
import RcTabs from 'rc-tabs';
import TabContent from 'rc-tabs/es/TabContent';
import classnames from 'classnames';
import omit from 'omit.js';

import { ConfigConsumer } from '../config-provider';
import Icons from '../icons';
import TabBar from './TabBar';
import './index.less';

const { CloseIcon, PlusSquareIcon } = Icons;

class Tabs extends React.Component {
  static defaultProps = {
    hideAdd: false,
    tabPosition: 'top',
  };

  componentDidMount() {
    const NO_FLEX = ' no-flex';
    const tabNode = ReactDOM.findDOMNode(this);
    if (
      tabNode &&
      !isFlexSupported &&
      tabNode.className.indexOf(NO_FLEX) === -1
    ) {
      tabNode.className += NO_FLEX;
    }
  }

  removeTab = (targetKey, e) => {
    e.stopPropagation();
    if (!targetKey) {
      return;
    }
    const { onEdit } = this.props;
    if (onEdit) {
      onEdit(targetKey, 'remove');
    }
  };

  createNewTab = targetKey => {
    const { onEdit } = this.props;
    if (onEdit) {
      onEdit(targetKey, 'add');
    }
  };

  handleChange = activeKey => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(activeKey);
    }
  };

  render() {
    return (
      <ConfigConsumer>
        {({ getPrefixCls, direction }) => {
          const {
            prefixCls: customizePrefixCls,
            className = '',
            size,
            children,
            type = 'line',
            hideAdd,
            tabPosition,
            animated = true,
            ...restProps
          } = this.props;

          const prefixCls = getPrefixCls('tabs');
          let tabPaneAnimated =
            typeof animated === 'object' ? animated.tabPane : animated;
          let { tabBarExtraContent } = this.props;
          // 禁用 card 动画
          if (type !== 'line') {
            tabPaneAnimated =
              'animated' in this.props ? tabPaneAnimated : false;
          }
          const cls = classnames(className, {
            [`${prefixCls}-vertical`]:
              tabPosition === 'left' || tabPosition === 'right',
            [`${prefixCls}-${size}`]: !!size,
            [`${prefixCls}-card`]: type.indexOf('card') >= 0,
            [`${prefixCls}-${type}`]: true,
            [`${prefixCls}-no-animation`]: !tabPaneAnimated,
          });
          // 自定义 关闭icon
          let childrenWithClose = [];
          if (type === 'editable-card') {
            React.Children.forEach(children, (child, index) => {
              if (!React.isValidElement(child)) return child;
              let { closable } = child.props;
              closable = typeof closable === 'undefined' ? true : closable;
              const closeIcon = closable ? (
                <CloseIcon
                  className={`${prefixCls}-close-x`}
                  onClick={e => this.removeTab(child.key, e)}
                />
              ) : null;
              childrenWithClose.push(
                React.cloneElement(child, {
                  tab: (
                    <div
                      className={
                        closable ? undefined : `${prefixCls}-tab-unclosable`
                      }
                    >
                      {child.props.tab}
                      {closeIcon}
                    </div>
                  ),
                  key: child.key || index,
                }),
              );
            });
            // 自定义加号 icon
            if (!hideAdd) {
              tabBarExtraContent = (
                <span>
                  <PlusSquareIcon
                    className={`${prefixCls}-new-tab`}
                    onClick={this.createNewTab}
                  />
                  {tabBarExtraContent}
                </span>
              );
            }
          }
          tabBarExtraContent = tabBarExtraContent ? (
            <div className={`${prefixCls}-extra-content`}>
              {tabBarExtraContent}
            </div>
          ) : null;
          const contentCls = classnames(
            `${prefixCls}-${tabPosition}-content`,
            type.indexOf('card') >= 0 && `${prefixCls}-card-content`,
          );
          const { ...tabBarProps } = this.props;
          return (
            <RcTabs
              {...restProps}
              prefixCls={prefixCls}
              className={cls}
              tabBarPosition={tabPosition}
              direction={direction}
              onChange={this.handleChange}
              renderTabBar={() => (
                <TabBar
                  {...omit(tabBarProps, ['className'])}
                  tabBarExtraContent={tabBarExtraContent}
                />
              )}
              renderTabContent={() => (
                <TabContent
                  className={contentCls}
                  animated={tabPaneAnimated}
                  animatedWithMargin
                />
              )}
            >
              {childrenWithClose.length > 0 ? childrenWithClose : children}
            </RcTabs>
          );
        }}
      </ConfigConsumer>
    );
  }
}

Tabs.TabPane = props => (
  <ConfigConsumer>
    {({ getPrefixCls }) => {
      const { prefixCls: customizePrefixCls, ...restProps } = props;
      const prefixCls = getPrefixCls('tabs');
      return <AntdTabs.TabPane {...restProps} prefixCls={prefixCls} />;
    }}
  </ConfigConsumer>
);

export default Tabs;
