import { lazy, Suspense, useState, useCallback, type ReactNode } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, Spin, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { getUser } from './store/auth';
import { ThemeProvider } from './store/theme';
import { useTheme } from './store/useTheme';

const LoginPage = lazy(() => import('./pages/LoginPage'));
const MainLayout = lazy(() => import('./layouts/MainLayout'));
const DashboardPage = lazy(() => import('./pages/DashboardPage'));
const AccountsPage = lazy(() => import('./pages/AccountsPage'));
const AssignmentsPage = lazy(() => import('./pages/AssignmentsPage'));
const LoginTasksPage = lazy(() => import('./pages/LoginTasksPage'));
const ProxyPage = lazy(() => import('./pages/ProxyPage'));
const UsersPage = lazy(() => import('./pages/UsersPage'));
const CookiePage = lazy(() => import('./pages/CookiePage'));
const HuyaAccountsPage = lazy(() => import('./pages/HuyaAccountsPage'));
const HuyaTasksPage = lazy(() => import('./pages/HuyaTasksPage'));

function RouteFallback() {
  return (
    <div style={{ minHeight: 160, display: 'grid', placeItems: 'center' }}>
      <Spin size="small" />
    </div>
  );
}

function lazyRoute(element: ReactNode) {
  return <Suspense fallback={<RouteFallback />}>{element}</Suspense>;
}

function AppContent() {
  // 用 state 驱动重渲染，登录/登出时调 refreshAuth()
  const [authVersion, setAuthVersion] = useState(0);
  const refreshAuth = useCallback(() => setAuthVersion((v) => v + 1), []);
  const isLoggedIn = !!getUser();
  const { isDark } = useTheme();

  return (
    <ConfigProvider
      locale={zhCN}
      theme={{
        algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
        token: {
          borderRadius: 6,
        },
      }}
    >
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={lazyRoute(<LoginPage onLogin={refreshAuth} />)} />
          <Route
            path="/"
            element={
              isLoggedIn
                ? lazyRoute(<MainLayout key={authVersion} onLogout={refreshAuth} />)
                : <Navigate to="/login" replace />
            }
          >
            <Route index element={lazyRoute(<DashboardPage />)} />
            <Route path="accounts" element={lazyRoute(<AccountsPage />)} />
            <Route path="assignments" element={lazyRoute(<AssignmentsPage />)} />
            <Route path="login-tasks" element={lazyRoute(<LoginTasksPage />)} />
            <Route path="cookies" element={lazyRoute(<CookiePage />)} />
            <Route path="huya/accounts" element={lazyRoute(<HuyaAccountsPage />)} />
            <Route path="huya/tasks" element={lazyRoute(<HuyaTasksPage />)} />
            <Route path="proxy" element={lazyRoute(<ProxyPage />)} />
            <Route path="users" element={lazyRoute(<UsersPage />)} />
          </Route>
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </BrowserRouter>
    </ConfigProvider>
  );
}

function App() {
  return (
    <ThemeProvider>
      <AppContent />
    </ThemeProvider>
  );
}

export default App;
