import { Tabs } from 'antd'
import type { TabsProps } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useTabStore } from '../stores/tabStore'

function TabBar() {
  const { tabs, activeKey, setActiveTab, closeTab } = useTabStore()
  const navigate = useNavigate()

  const handleChange = (key: string) => {
    setActiveTab(key)
    navigate(key)
  }

  const items: TabsProps['items'] = tabs.map((tab) => ({
    key: tab.key,
    label: (
      <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        {tab.icon && <span style={{ fontSize: 13 }}>{tab.icon}</span>}
        {tab.title}
      </span>
    ),
    closeIcon: tab.closable ? <CloseOutlined style={{ fontSize: 10 }} /> : false,
  }))

  return (
    <div
      style={{
        background: '#fff',
        borderBottom: '1px solid #e5e7eb',
        flexShrink: 0,
        paddingLeft: 4,
      }}
    >
      <Tabs
        type="editable-card"
        hideAdd
        activeKey={activeKey}
        onChange={handleChange}
        onEdit={(key, action) => {
          if (action === 'remove') {
            closeTab(key as string)
            navigate(useTabStore.getState().activeKey)
          }
        }}
        items={items}
        style={{ marginBottom: 0 }}
        tabBarStyle={{ margin: 0, border: 'none' }}
      />
    </div>
  )
}

export default TabBar
