import Button from '../../button';
import Icon from '../../icon';
import React from 'react';
import ReactDOM from 'react-dom';
import Tab from '..';
const panes = [
  { tab: 'Mail', key: 1, closeable: false },
  { tab: 'Message', key: 2, closeable: true },
  { tab: 'Setting', key: 3, closeable: true },
  { tab: 'Unread', key: 4, closeable: true },
];
interface PageStates {
  activeKey: any;
  panes: Array<any>;
}
class CloseableTab extends React.Component<{}, PageStates> {
  onClose: (targetKey: any) => void;
  onChange: (activeKey: any) => void;
  addTabpane: () => void;
  constructor(props) {
    super(props);
    this.onClose = targetKey => {
      this.remove(targetKey);
    };
    this.onChange = activeKey => {
      this.setState({ activeKey });
    };
    this.addTabpane = () => {
      this.setState(prevState => {
        const { panes } = prevState;
        panes.push({ tab: 'new tab', key: Math.random(), closeable: true });
        return { panes };
      });
    };
    this.state = {
      panes,
      activeKey: panes[0].key,
    };
  }

  /* eslint-disable eqeqeq */
  remove(targetKey) {
    let activeKey = this.state.activeKey;
    const panes = [];
    this.state.panes.forEach(pane => {
      if (pane.key != targetKey) {
        panes.push(pane);
      }
    });

    if (targetKey == activeKey) {
      activeKey = panes[0].key;
    }
    this.setState({ panes, activeKey });
  }

  render() {
    const state = this.state;
    return (
      <div>
        <Button onClick={this.addTabpane} type="primary">
          <Icon type="add" /> New Tab
        </Button>
        <Tab
          shape="wrapped"
          activeKey={state.activeKey}
          onChange={this.onChange}
          onClose={this.onClose}
          className="custom-tab"
        >
          {state.panes.map(item => (
            <Tab.Item
              title={item.tab}
              key={item.key}
              closeable={item.closeable}
            >
              {item.tab} content
            </Tab.Item>
          ))}
        </Tab>
        <br />
        <br />
        <Tab
          shape="wrapped"
          activeKey={state.activeKey}
          onChange={this.onChange}
          onClose={this.onClose}
          className="custom-tab"
          size='large'
        >
          {state.panes.map(item => (
            <Tab.Item
              title={item.tab}
              key={item.key}
              closeable={item.closeable}
            >
              {item.tab} content
            </Tab.Item>
          ))}
        </Tab>
      </div>
    );
  }
}

ReactDOM.render(<CloseableTab />, document.getElementById('tab-demo-7'));
