import { useEffect, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { PageContainer, ProLayout } from '@ant-design/pro-components';
import { Button, Dropdown } from 'antd';
import { DesktopOutlined, MoonOutlined, SunOutlined } from '@ant-design/icons';

import PageSkeleton from '@/components/PageSkeleton';
import { usePermissionStore } from '@/stores/permission';
import { useUserStore } from '@/stores/user';
import { menusToProRoutes } from '@/router/menu';
import logo from '@/assets/logo.png';
import { useAppStore } from '@/stores/app';
import { useResolvedTheme } from '@/hooks/useTheme';
import type { ThemePreference } from '@/stores/app';

export default function BasicLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const menus = usePermissionStore(s => s.menus);
  const clearMenus = usePermissionStore(s => s.clearMenus);
  const userInfo = useUserStore(s => s.userInfo);
  const logout = useUserStore(s => s.logout);
  const preference = useAppStore(s => s.themePreference);
  const setThemePreference = useAppStore(s => s.setThemePreference);
  const resolved = useResolvedTheme();
  const [contentReady, setContentReady] = useState(false);

  useEffect(() => {
    // 等 ProLayout / 侧栏完成首屏布局后再挂页面（图表）
    const id = requestAnimationFrame(() => {
      setContentReady(true);
    });
    return () => cancelAnimationFrame(id);
  }, []);

  const proRoutes = {
    path: '/',
    routes: menusToProRoutes(menus),
  };

  const icon = preference === 'system' ? <DesktopOutlined /> : resolved === 'dark' ? <MoonOutlined /> : <SunOutlined />;

  return (
    <ProLayout
      logo={<img src={logo} alt="logo" />}
      title="ChatOne"
      layout="mix" // 或 side
      location={{ pathname: location.pathname }}
      route={proRoutes}
      menuProps={{
        onClick: ({ key }) => {
          // key 一般是 path，如 /dashboard、/llm
          if (!key || key.startsWith('http')) return;
          navigate(key);
        },
      }}
      avatarProps={{
        title: userInfo?.nickname ?? '用户',
        render: (_, dom) => (
          <Dropdown
            menu={{
              items: [{ key: 'logout', label: '退出登录' }],
              onClick: ({ key }) => {
                if (key === 'logout') {
                  logout();
                  clearMenus();
                  navigate('/login', { replace: true });
                }
              },
            }}
          >
            {dom}
          </Dropdown>
        ),
      }}
      actionsRender={() => [
        <Dropdown
          menu={{
            items: [
              { key: 'light', label: '亮色', icon: <SunOutlined /> },
              { key: 'dark', label: '暗色', icon: <MoonOutlined /> },
              { key: 'system', label: '跟随系统', icon: <DesktopOutlined /> },
            ],
            selectable: true,
            selectedKeys: [preference],
            onClick: ({ key }) => setThemePreference(key as ThemePreference),
          }}
        >
          <Button type="text" icon={icon} />
        </Dropdown>,
      ]}
    >
      <PageContainer>{contentReady ? <Outlet /> : <PageSkeleton />}</PageContainer>
    </ProLayout>
  );
}
