import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
import React, { lazy, Suspense } from "react";
import LoadingComponent from "./components/Loading";
import DashboardLayout from "./layouts/DashboardLayout";
import RoleList from "./pages/RoleList";
import AddEditRolePage from "./pages/AddEditRolePage";

// Page imports
const Login = lazy(() => import("./pages/Auth/Login"));
const SignUp = lazy(() => import("./pages/Auth/SignUp"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Vehicles = lazy(() => import("./pages/Vehicles"));
const AdminList = lazy(() => import("./pages/AdminList"));
const ProfilePage = lazy(() => import("./pages/ProfilePage"));
const NotFoundPage = lazy(() => import("./pages/NotFound"));
const UserList = lazy(() => import("./pages/UserList"));

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

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

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

				{/* Auth Routes */}
				<Route path="">
					<Route
						path=""
						element={<Navigate to="/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="user-list"
						element={
							<ProtectedRoute
								caps={[]}
								component={<UserList />}
							/>
						}
					/>
					<Route
						path="role-list"
						element={
							<ProtectedRoute
								caps={[]}
								component={<RoleList />}
							/>
						}
					/>
					<Route
						path="permissions"
						element={
							<ProtectedRoute
								caps={[]}
								component={<AddEditRolePage />}
							/>
						}
					/>
					<Route
						path="profile"
						element={
							<ProtectedRoute
								caps={[]}
								component={<ProfilePage />}
							/>
						}
					/>
				</Route>

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