import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { DashboardLayout, type SidebarItem } from "@edr/ui-common";
import { LayoutDashboard, ShieldCheck, Users, Network } from "lucide-react";

import { useAuth } from "./auth/useAuth";
import LoginPage from "./pages/auth/LoginPage";
import OverviewPage from "./pages/dashboard/OverviewPage";
import UsersPage from "./pages/dashboard/user-management/UsersPage";
import RolesPage from "./pages/dashboard/user-management/RolesPage";
import DepartmentsPage from "./pages/dashboard/user-management/DepartmentsPage";
import OrgStructurePage from "./pages/dashboard/org-structure/OrgStructurePage";
import LoadingScreen from "./components/LoadingScreen";

const sidebarItems: SidebarItem[] = [
  {
    label: "Overview",
    href: "/dashboard/overview",
    icon: <LayoutDashboard />,
  },
  {
    label: "Org structure",
    href: "/dashboard/org-structure",
    icon: <Network />,
  },
];

const DashboardShell = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuth();

  const displayName = user?.name?.en || user?.username || user?.email || "User";

  return (
    <DashboardLayout
      title="EDR Freight Backoffice"
      sidebarItems={sidebarItems}
      activeHref={location.pathname}
      onNavigate={navigate}
      enableThemeToggle
      userName={displayName}
      userEmail={user?.email}
      onLogout={logout}
    >
      <Outlet />
    </DashboardLayout>
  );
};

const App = () => {
  const { user, loading } = useAuth();

  if (loading) {
    return <LoadingScreen />;
  }

  if (!user) {
    return (
      <Routes>
        <Route path="/auth" element={<LoginPage />} />
        <Route path="*" element={<Navigate to="/auth" replace />} />
      </Routes>
    );
  }

  return (
    <Routes>
      <Route path="/" element={<Navigate to="/dashboard/overview" replace />} />
      <Route path="/dashboard" element={<Navigate to="/dashboard/overview" replace />} />
      <Route path="/dashboard" element={<DashboardShell />}>
        <Route path="overview" element={<OverviewPage />} />
        <Route path="org-structure" element={<OrgStructurePage />} />
        <Route path="org-structure/units/:unitId" element={<OrgStructurePage />} />
        <Route path="org-structure/units/:unitId/:section" element={<OrgStructurePage />} />
      </Route>
      <Route path="*" element={<Navigate to="/dashboard/overview" replace />} />
    </Routes>
  );
};

export default App;
