import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useEffect } from 'react';
import TabLayout from './layouts/TabLayout';
import LoginPage from './pages/LoginPage';
import HomePage from './pages/HomePage';
import StoreListPage from './pages/StoreListPage';
import StoreDetailPage from './pages/StoreDetailPage';
import StoreCreatePage from './pages/StoreCreatePage';
import OrderListPage from './pages/OrderListPage';
import OrderDetailPage from './pages/OrderDetailPage';
import CenterPage from './pages/CenterPage';
import BillsPage from './pages/BillsPage';
import ReshipPage from './pages/ReshipPage';
import WeeklyReportPage from './pages/WeeklyReportPage';
import LeaderboardPage from './pages/LeaderboardPage';
import { handlePartnerWechatCallback, savePartnerWechatAuth } from './lib/wechat-auth';
import { isWechatEnv } from './lib/weixin';

function WechatOAuthHandler() {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (!isWechatEnv() || !location.search.includes('code=')) return;
    if (location.pathname === '/login') return;
    void handlePartnerWechatCallback()
      .then((result) => {
        if (!result || !savePartnerWechatAuth(result)) return;
        const params = new URLSearchParams(location.search);
        params.delete('code');
        params.delete('state');
        const qs = params.toString();
        navigate(`${location.pathname}${qs ? `?${qs}` : ''}`, { replace: true });
      })
      .catch(() => {
        /* 页面内组件会提示 */
      });
  }, [location.pathname, location.search, navigate]);

  return null;
}

export default function App() {
  return (
    <>
      <WechatOAuthHandler />
      <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route element={<TabLayout />}>
        <Route path="/" element={<HomePage />} />
        <Route path="/stores" element={<StoreListPage />} />
        <Route path="/orders" element={<OrderListPage />} />
        <Route path="/center" element={<CenterPage />} />
      </Route>
      <Route path="/stores/new" element={<StoreCreatePage />} />
      <Route path="/center/bills" element={<BillsPage />} />
      <Route path="/reshipments" element={<ReshipPage />} />
      <Route path="/reports/weekly" element={<WeeklyReportPage />} />
      <Route path="/leaderboard" element={<LeaderboardPage />} />
      <Route path="/stores/:id" element={<StoreDetailPage />} />
      <Route path="/orders/:id" element={<OrderDetailPage />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
    </>
  );
}
