import { lazy, Suspense, useState, useCallback, type ReactNode } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { App as AntdApp, 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';
import AntdMessageBridge from './utils/AntdMessageBridge';

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 AccountCheckPage = lazy(() => import('./pages/AccountCheckPage'));
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 DouyuTasksPage = lazy(() => import('./pages/DouyuTasksPage'));
const HuyaAccountsPage = lazy(() => import('./pages/HuyaAccountsPage'));
const HuyaAssignmentsPage = lazy(() => import('./pages/HuyaAssignmentsPage'));
const HuyaCookiePage = lazy(() => import('./pages/HuyaCookiePage'));
const HuyaRegisterPage = lazy(() => import('./pages/HuyaRegisterPage'));
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,
        },
      }}
    >
      <AntdApp>
        <AntdMessageBridge />
        <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="account-check" element={lazyRoute(<AccountCheckPage />)} />
              <Route path="assignments" element={lazyRoute(<AssignmentsPage />)} />
              <Route path="login-tasks" element={lazyRoute(<LoginTasksPage />)} />
              <Route path="cookies" element={lazyRoute(<CookiePage />)} />
              <Route path="douyu/tasks" element={<Navigate to="/douyu/elite" replace />} />
              <Route path="douyu/elite" element={lazyRoute(<DouyuTasksPage handbook="elite" />)} />
              <Route path="douyu/esports" element={lazyRoute(<DouyuTasksPage handbook="esports" />)} />
              <Route path="douyu/peace" element={lazyRoute(<DouyuTasksPage handbook="peace" />)} />
              <Route path="huya/accounts" element={lazyRoute(<HuyaAccountsPage />)} />
              <Route path="huya/register" element={lazyRoute(<HuyaRegisterPage />)} />
              <Route path="huya/assignments" element={lazyRoute(<HuyaAssignmentsPage />)} />
              <Route path="huya/cookies" element={lazyRoute(<HuyaCookiePage />)} />
              <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>
      </AntdApp>
    </ConfigProvider>
  );
}

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

export default App;
