import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { authApi } from './services/api';
import LoginPage from './pages/Login';
import AdminLayout from './components/AdminLayout';
import PublicQueryPage from './pages/PublicQuery';
import DashboardPage from './pages/Dashboard';
import ManagePage from './pages/Manage';
import ProfilePage from './pages/Profile';
import EmployeeSerialsPage from './pages/EmployeeSerials';
import AftersalesPage from './pages/Aftersales';
import AftersalesDetailPage from './pages/AftersalesDetail';
import AftersalesConfirmPage from './pages/AftersalesConfirm';
import UsersPage from './pages/Users';

const PrivateRoute = () => {
  const user = authApi.getCurrentUser();
  if (!user) {
    return <Navigate to="/login" replace />;
  }
  return <Outlet />;
};

const PublicRoute = ({ children }: { children: React.ReactNode }) => {
  const user = authApi.getCurrentUser();
  if (user) {
    return <Navigate to="/admin/dashboard" replace />;
  }
  return <>{children}</>;
};

const AdminRoutes = () => {
  return <AdminLayout />;
};

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navigate to="/login" replace />} />
        <Route path="/login" element={
          <PublicRoute>
            <LoginPage />
          </PublicRoute>
        } />
        <Route path="/query" element={<PublicQueryPage />} />
        <Route path="/aftersales/:serialNumber" element={<AftersalesConfirmPage />} />

        <Route element={<PrivateRoute />}>
          <Route element={<AdminRoutes />}>
            <Route path="/admin" element={<Navigate to="dashboard" replace />} />
            <Route path="/admin/dashboard" element={<DashboardPage />} />
            <Route path="/admin/manage" element={<ManagePage />} />
            <Route path="/admin/employee-serials" element={<EmployeeSerialsPage />} />
            <Route path="/admin/aftersales" element={<AftersalesPage />} />
            <Route path="/admin/aftersales/:serialNumber" element={<AftersalesDetailPage />} />
            <Route path="/admin/users" element={<UsersPage />} />
            <Route path="/admin/profile" element={<ProfilePage />} />
          </Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
