import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import { useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router';
import { routes } from '@/routes';
import { toMenuItems } from '@/routes/utils';

const { Header, Sider, Content } = Layout;

const menuItems = toMenuItems(routes);

const RootLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);

  return (
    <Layout style={{ height: '100vh' }}>
      <Header
        style={{
          display: 'flex',
          alignItems: 'center',
          padding: '0 24px',
          background: '#fff',
          borderBottom: '1px solid #f0f0f0',
        }}
      >
        <span style={{ fontWeight: 'bold', fontSize: 18 }}>TaoTie</span>
      </Header>
      <Layout style={{ overflow: 'hidden' }}>
        <Sider
          theme="light"
          width={200}
          collapsed={collapsed}
          style={{ borderRight: '1px solid #f0f0f0', position: 'relative' }}
        >
          <Menu
            mode="inline"
            selectedKeys={[location.pathname]}
            defaultOpenKeys={menuItems.map((item) => item.key)}
            items={menuItems}
            onClick={({ key }) => navigate(key)}
            style={{ height: '100%', borderRight: 0, paddingBottom: 48 }}
          />
          <div
            onClick={() => setCollapsed(!collapsed)}
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              height: 48,
              display: 'flex',
              alignItems: 'center',
              justifyContent: collapsed ? 'center' : 'flex-end',
              padding: collapsed ? 0 : '0 24px',
              borderTop: '1px solid #f0f0f0',
              cursor: 'pointer',
              color: '#666',
              background: '#fff',
              transition: 'all 0.2s',
              userSelect: 'none',
            }}
          >
            {collapsed ? (
              <MenuUnfoldOutlined />
            ) : (
              <>
                <MenuFoldOutlined style={{ marginRight: 8 }} />
                <span style={{ fontSize: 13 }}>收起</span>
              </>
            )}
          </div>
        </Sider>
        <Content style={{ padding: 0, overflow: 'auto' }}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default RootLayout;
