import { Tabs, Icon } from '@btri-ui/base';
import React, { useRef, useState } from 'react';

const { TabPane } = Tabs;

const initialPanes = [
  { title: '选项一', content: '选项一的内容', key: '1' },
  { title: '选项二', content: '选项二的内容', key: '2' },
  {
    title: '选项三',
    content: '选项三',
    key: '3',
  },
];

const App: React.FC = () => {
  const [activeKey, setActiveKey] = useState(initialPanes[0].key);
  const [panes, setPanes] = useState(initialPanes);
  const newTabIndex = useRef(0);

  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
  };

  const add = () => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    const newPanes = [...panes];
    newPanes.push({
      title: `选项`,
      content: '新选项内容',
      key: newActiveKey,
    });
    setPanes(newPanes);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: string) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = panes.filter(pane => pane.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setPanes(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (targetKey: string, action: 'add' | 'remove') => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  return (
    <Tabs
      type="editable-card"
      onChange={onChange}
      activeKey={activeKey}
      onEdit={onEdit}
    >
      {panes.map(pane => (
        <TabPane
          tab={pane.title}
          key={pane.key}
          closable={pane.closable}
          closeIcon={<Icon iconName="CloseSmall" />}
        >
          {pane.content}
        </TabPane>
      ))}
    </Tabs>
  );
};

export default App;
