import {
	Routes as BaseRoutes,
	Navigate,
	Route,
	RouteProps,
} from "react-router-dom";
import React, { Suspense } from "react";
import { useSelector } from "react-redux";
import { RootState } from "./redux/store/store";
import LoadingComponent from "./components/Loading";
import DashboardLayout from "./layouts/DashboardLayout";

// Page imports
import Login from "./pages/Auth/Login";
import SignUp from "./pages/Auth/SignUp";
import Dashboard from "./pages/Dashboard";
import Vehicles from "./pages/Vehicles";
import AdminList from "./pages/AdminList";
import ProfilePage from "./pages/ProfilePage";

interface ProtectedRouteProps {
	caps: string[];
	component: React.ReactNode;
}

// Protected Route Component
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ caps, component }) => {
	if (!localStorage.getItem("authToken")) {
		return <Navigate to="/auth/login" replace />;
	}
	return <>{component}</>;
};

// Combined Router Component
export default function AppRouter() {
	return (
		<Suspense fallback={<LoadingComponent />}>
			<BaseRoutes>
				{/* Default Route */}
				<Route element={<Navigate to="/auth/login" replace />} index />

				{/* Auth Routes */}
				<Route path="/auth">
					<Route
						path=""
						element={<Navigate to="/auth/login" replace />}
						index
					/>
					<Route path="login" element={<Login />} />
					<Route path="signup" element={<SignUp />} />
				</Route>

				{/* Dashboard Routes */}
				<Route path="/panel" element={<DashboardLayout />}>
					<Route
						path="dashboard"
						element={
							<ProtectedRoute
								caps={[]}
								component={<Dashboard />}
							/>
						}
					/>
					<Route
						path="vehicles"
						element={
							<ProtectedRoute
								caps={[]}
								component={<Vehicles />}
							/>
						}
					/>
					<Route
						path="admin-list"
						element={
							<ProtectedRoute
								caps={[]}
								component={<AdminList />}
							/>
						}
					/>

					<Route
						path="profile"
						element={
							<ProtectedRoute
								caps={[]}
								component={<ProfilePage />}
							/>
						}
					/>
				</Route>

				{/* Catch-all Route */}
				<Route path="*" element={<>404</>} />
			</BaseRoutes>
		</Suspense>
	);
}
