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;
}

interface SuperAdminRouteProps {
	children: React.ReactNode;
}

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

// Super Admin Route Component
const SuperAdminRoute: React.FC<SuperAdminRouteProps> = ({ children }) => {
	const userRole = useSelector(
		(state: RootState) => state.profileReducer.user?.role
	);

	if (userRole !== "superadmin") {
		return <Navigate to="/panel/dashboard" replace />;
	}
	return <>{children}</>;
};

// 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
						path="profile"
						element={
							<ProtectedRoute
								caps={[]}
								component={<ProfilePage />}
							/>
						}
					/>
				</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="adminlist"
						element={
							<ProtectedRoute
								caps={[]}
								component={
									<SuperAdminRoute>
										<AdminList />
									</SuperAdminRoute>
								}
							/>
						}
					/>
					<Route path="*" element={<>404</>} />
				</Route>

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