import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import {
  Boxes,
  FileText,
  LayoutDashboard,
  Network,
  Paperclip,
  Settings,
  SlidersHorizontal,
  Train,
  Truck,
  Container,
  Package,
  //TrainTrack,
} from "lucide-react";

import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@/components/layout";
import LoadingScreen from "./components/LoadingScreen";
import { useAuth } from "./auth/useAuth";
import LoginPage from "./pages/auth/LoginPage";
import BookingContractPage from "./pages/bookings/BookingContractPage";
import BookingRequestDetailPage from "./pages/bookings/BookingRequestDetailPage";
import BookingRequestsPage from "./pages/bookings/BookingRequestsPage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page";
import DemoUser2Page from "./pages/dashboard/demo/DemoUser2Page";
import OverviewPage from "./pages/dashboard/OverviewPage";
//import EmployeesPage from "./pages/dashboard/user-management/EmployeesPage";
import PermissionsPage from "./pages/dashboard/user-management/PermissionsPage";
import PositionTypesPage from "./pages/dashboard/user-management/PositionTypesPage";
import RolesPage from "./pages/dashboard/user-management/RolesPage";
import UserManagementPage from "./pages/dashboard/user-management/UserManagementPage";
import UsersPage from "./pages/dashboard/user-management/UsersPage";
import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage";
import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirect";
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
import TrainsPage from "./pages/trains/TrainsPage";
import TrainScheduleV2ListPage from "./pages/trainScheduling/TrainScheduleV2ListPage";
import TrainScheduleV2DetailPage from "./pages/trainScheduling/TrainScheduleV2DetailPage";
import TrainSchedulingGlobalRulesPage from "./pages/trainScheduling/TrainSchedulingGlobalRulesPage";
import FleetResourcePage from "./pages/fleet/FleetResourcePage";
import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources";
import TrainDetailPage from "./pages/trains/TrainDetailPage";
import RoutesPage from "./pages/fleet/RoutesPage";

const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
  {
    title: "Main menu",
    mutedTitle: true,
    items: [
      {
        label: "Overview",
        href: "/dashboard/overview",
        icon: <LayoutDashboard />,
      },
      {
        label: "Booking requests",
        href: "/dashboard/booking-requests",
        icon: <FileText />,
      },
      ...demoItems,
    ],
  },
  {
    title: "Operations",
    items: [
      {
        label: "Train Schedules",
        href: "/dashboard/operations/train-scheduling",
        icon: <Train />,
      },
      {
        label: "Train Schedules v2",
        href: "/dashboard/operations/train-scheduling-v2",
        icon: <Train />,
      },
    ],
  },
  {
    title: "Fleet Management",
    items: [
      {
        label: "Routes",
        href: "/dashboard/routes",
        icon: <Network />,
      },
      {
        label: "Locomotives",
        href: "/dashboard/locomotives",
        icon: <Train />,
      },
      {
        label: "Trains",
        href: "/dashboard/trains",
        icon: <Train />,
      },
      {
        label: "Wagons",
        href: "/dashboard/wagons",
        icon: <Truck />,
      },
      {
        label: "Containers",
        href: "/dashboard/containers",
        icon: <Container />,
      },
      {
        label: "Cargoes",
        href: "/dashboard/cargoes",
        icon: <Package />,
      },
    ],
  },
  {
    title: "Administration",
    items: [
      {
        label: "User management",
        href: "/dashboard/user-management",
        icon: <Network />,
        children: [
          {
            label: "Users",
            href: "/dashboard/user-management/users",
          },
          {
            label: "Employees",
            href: "/dashboard/user-management/employees",
          },
          {
            label: "Position Types",
            href: "/dashboard/user-management/position-types",
          },
          {
            label: "Permissions",
            href: "/dashboard/user-management/permissions",
          },
          {
            label: "Roles",
            href: "/dashboard/user-management/roles",
          },
        ],
      },
      {
        label: "File settings",
        href: "/dashboard/file-settings",
        icon: <Paperclip />,
      },
      {
        label: "Dropdown settings",
        href: "/dashboard/dropdown-settings",
        icon: <Settings />,
      },
    ],
  },
  {
    title: "Freight configuration",
    mutedTitle: true,
    items: [
      {
        label: "Configuration",
        href: "/dashboard/configuration",
        icon: <Boxes />,
        children: [
          ...getCategorySidebarChildren("configuration"),
          {
            label: "Train scheduling rules",
            href: "/dashboard/configuration/train-scheduling-rules",
          },
        ],
      },
      {
        label: "Rules",
        href: "/dashboard/rules",
        icon: <SlidersHorizontal />,
        children: getCategorySidebarChildren("rules"),
      },
    ],
  },
];

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 demoItems: SidebarItem[] = [];

  const sidebarSections = buildSidebarSections(demoItems);
  const displayName = user?.name?.en || user?.username || user?.email || "User";

  return (
    <FreightDashboardLayout
      sidebarSections={sidebarSections}
      activeHref={location.pathname}
      onNavigate={navigate}
      enableThemeToggle
      userName={displayName}
      userEmail={user?.email}
      onLogout={logout}
    >
      <Outlet />
    </FreightDashboardLayout>
  );
};

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="booking-requests" element={<BookingRequestsPage />} />
          <Route path="booking-requests/new" element={<NewBookingPage />} />
          <Route path="booking-requests/:id" element={<BookingRequestDetailPage />} />
          <Route
            path="booking-requests/:id/contract"
            element={<BookingContractPage />}
          />
          <Route path="operations/train-scheduling" element={<TrainsPage />} />
          <Route
            path="operations/train-scheduling-v2"
            element={<TrainScheduleV2ListPage />}
          />
          <Route
            path="operations/train-scheduling-v2/:scheduleId"
            element={<TrainScheduleV2DetailPage />}
          />
          <Route path="routes" element={<RoutesPage />} />
          <Route path="locomotives" element={<FleetResourcePage />} />
          <Route path="trains" element={<FleetResourcePage />} />
          <Route path="trains/:id" element={<TrainDetailPage />} />
          <Route path="wagons" element={<FleetResourcePage />} />
          <Route path="containers" element={<FleetResourcePage />} />
          <Route path="cargoes" element={<FleetResourcePage />} />

          <Route path="user-management" element={<UserManagementPage />} />
          <Route path="user-management/users" element={<UsersPage />} />
          <Route path="user-management/position-types" element={<PositionTypesPage />} />
          {/* <Route path="user-management/employees" element={<EmployeesPage />} /> */}
          <Route path="user-management/permissions" element={<PermissionsPage />} />
          <Route path="user-management/roles" element={<RolesPage />} />

          <Route path="file-settings" element={<FileUploadSettingsPage />} />
          <Route path="dropdown-settings" element={<DropdownSettingsPage />} />

          <Route
            path="configuration"
            element={<Navigate to="/dashboard/configuration/cargo-types" replace />}
          />
          <Route
            path="configuration/train-scheduling-rules"
            element={<TrainSchedulingGlobalRulesPage />}
          />
          <Route path="configuration/:resource" element={<RuleEngineResourcePage />} />

          <Route
            path="rules"
            element={<Navigate to="/dashboard/rules/priority-rules" replace />}
          />
          <Route path="rules/:resource" element={<RuleEngineResourcePage />} />

          <Route
            path="rule-engine"
            element={<Navigate to="/dashboard/configuration/cargo-types" replace />}
          />
          <Route path="rule-engine/:resource" element={<RuleEngineLegacyRedirect />} />

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