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

import { useAuth } from "./auth/useAuth";
import LoginPage from "./pages/auth/LoginPage";
import OverviewPage from "./pages/dashboard/OverviewPage";
import EmployeesPage from "./pages/dashboard/user-management/EmployeesPage";
import PermissionsPage from "./pages/dashboard/user-management/PermissionsPage";
import RolesPage from "./pages/dashboard/user-management/RolesPage";
import UserManagementPage from "./pages/dashboard/user-management/UserManagementPage";
import LoadingScreen from "./components/LoadingScreen";
import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page";
import DemoUser2Page from "./pages/dashboard/demo/DemoUser2Page";

const hasPermission = (
  user: ReturnType<typeof useAuth>["user"],
  key: string,
) => {
  if (!user) return false;
  if (user.permissions?.some((p) => p.key === key)) return true;
  return (user.employee ?? []).some((emp) =>
    (emp.positions ?? []).some((pos) =>
      (pos.permissions ?? []).some((p) => p.key === key),
    ),
  );
};

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

  const sidebarItems: SidebarItem[] = [
    {
      label: "Overview",
      href: "/dashboard/overview",
      icon: <LayoutDashboard />,
    },
    {
      label: "User management",
      href: "/dashboard/user-management",
      icon: <Network />,
      children: [
        {
          label: "Employees",
          href: "/dashboard/user-management/employees",
        },
        {
          label: "Permissions",
          href: "/dashboard/user-management/permissions",
        },
        {
          label: "Roles",
          href: "/dashboard/user-management/roles",
        },
      ],
    },
    {
      label: "Rule Engine",
      href: "/dashboard/rule-engine",
      icon: <Settings />,
    },
    ...(hasPermission(user, "can:demo:user1")
      ? ([
          {
            label: "User1",
            href: "/dashboard/user1",
            icon: <Settings />,
          },
        ] as SidebarItem[])
      : []),
    ...(hasPermission(user, "can:demo:user2")
      ? ([
          {
            label: "User2",
            href: "/dashboard/user2",
            icon: <Settings />,
          },
        ] as SidebarItem[])
      : []),
  ];

  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="user-management" element={<UserManagementPage />} />

        <Route path="rule-engine" element={<RuleEnginePage />} />

        <Route path="user-management/employees" element={<EmployeesPage />} />
        <Route path="user-management/permissions" element={<PermissionsPage />} />
        <Route path="user-management/roles" element={<RolesPage />} />

        <Route path="user1" element={<DemoUser1Page />} />
        <Route path="user2" element={<DemoUser2Page />} />
        <Route path="org-structure" element={<Navigate to="/dashboard/user-management" replace />} />
        <Route path="org-structure/*" element={<Navigate to="/dashboard/user-management" replace />} />
      </Route>
      <Route path="*" element={<Navigate to="/dashboard/overview" replace />} />
    </Routes>
  );
};

export default App;
