import {
  Boxes,
  Building2,
  Container,
  FileText,
  LayoutDashboard,
  LayoutGrid,
  Network,
  Package,
  PackageCheck,
  PackageOpen,
  Paperclip,
  Send,
  Settings,
  ShieldCheck,
  SlidersHorizontal,
  Train,
  Truck,
  Users,
  Wallet,
} from "lucide-react";
import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom";

import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@/components/layout";
import { useAuth } from "./auth/useAuth";
import LoadingScreen from "./components/LoadingScreen";
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 GlClearancePage from "./pages/bookings/GlClearancePage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import CustomerDetailPage from "./pages/customers/CustomerDetailPage";
import CustomersPage from "./pages/customers/CustomersPage";
import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page";
import DemoUser2Page from "./pages/dashboard/demo/DemoUser2Page";
import MyProfilePage from "./pages/dashboard/MyProfilePage";
import OverviewPage from "./pages/dashboard/OverviewPage";
import UserManagementHostPage from "./pages/dashboard/user-management/UserManagementHostPage";
import PaymentsPage from "./pages/payments/PaymentsPage";
//import EmployeesPage from "./pages/dashboard/user-management/EmployeesPage";
import { RequirePermission } from "./components/auth/RequirePermission";
import { FREIGHT_PERMS, hasPermission as hasFreightPermission } from "./lib/permissions";
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 FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage";
import FleetResourcePage from "./pages/fleet/FleetResourcePage";
import RoutesPage from "./pages/fleet/RoutesPage";
import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources";
import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirect";
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
import CargoTypesPage from "./pages/ruleEngine/CargoTypesPage";
import TrainScheduleV2ListPage from "./pages/trainScheduling/TrainScheduleV2ListPage";
import BatchBoardPage from "./pages/trainScheduling/BatchBoardPage";
import BatchScheduleDetailPage from "./pages/trainScheduling/BatchScheduleDetailPage";
import TrainScheduleV2DetailPage from "./pages/trainScheduling/TrainScheduleV2DetailPage";
import TrainScheduleTrackPage from "./pages/trainScheduling/TrainScheduleTrackPage";
import TrainSchedulingGlobalRulesPage from "./pages/trainScheduling/TrainSchedulingGlobalRulesPage";
import FirstMilePage from "./pages/operations/FirstMilePage";
import LastMilePage from "./pages/operations/LastMilePage";
import TrainDetailPage from "./pages/trains/TrainDetailPage";
import ArrivalQueuePage from "./pages/warehouses/ArrivalQueuePage";
import DispatchQueuePage from "./pages/warehouses/DispatchQueuePage";
import InventoryInquiryPage from "./pages/warehouses/InventoryInquiryPage";
import LoadedInventoryPage from "./pages/warehouses/LoadedInventoryPage";
import LoadingQueuePage from "./pages/warehouses/LoadingQueuePage";
import WarehouseDashboardPage from "./pages/warehouses/WarehouseDashboardPage";
import WarehouseDetailPage from "./pages/warehouses/WarehouseDetailPage";
import WarehouseInventoryPage from "./pages/warehouses/WarehouseInventoryPage";
import WarehouseInvoicesPage from "./pages/warehouses/WarehouseInvoicesPage";
import WarehouseListPage from "./pages/warehouses/WarehouseListPage";
import WarehouseRulesPage from "./pages/warehouses/WarehouseRulesPage";

const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
  {
    title: "Main menu",
    items: [
      {
        label: "Overview",
        href: "/dashboard/overview",
        icon: <LayoutDashboard />,
      },
      {
        label: "UM",
        href: "/um",
        icon: <Users />,
      },
      {
        label: "Booking requests",
        href: "/dashboard/booking-requests",
        icon: <FileText />,
      },
      {
        label: "Customers",
        href: "/dashboard/customers",
        icon: <Building2 />,
      },
      {
        label: "Payments",
        href: "/dashboard/payments",
        icon: <Wallet />,
        permission: FREIGHT_PERMS.bookings.view,
      },
      ...demoItems,
    ],
  },
  {
    title: "Operations",
    items: [
      {
        label: "Document Clearance",
        href: "/dashboard/clearance",
        icon: <ShieldCheck />,
        permission: FREIGHT_PERMS.bookings.reviewDocuments,
      },
      {
        label: "Train Schedules",
        href: "/dashboard/operations/train-scheduling-v2",
        icon: <Train />,
        permission: FREIGHT_PERMS.trainScheduling.view,
      },
      {
        label: "Batch Board",
        href: "/dashboard/operations/batch-board",
        icon: <LayoutGrid />,
        permission: FREIGHT_PERMS.trainScheduling.view,
      },
      {
        label: "First Mile",
        href: "/dashboard/operations/first-mile",
        icon: <Truck />,
        permission: FREIGHT_PERMS.trainScheduling.view,
      },
      {
        label: "Last Mile",
        href: "/dashboard/operations/last-mile",
        icon: <Truck />,
        permission: FREIGHT_PERMS.trainScheduling.view,
      },
    ],
  },
  {
    title: "Fleet Management",
    items: [
      {
        label: "Routes",
        href: "/dashboard/routes",
        icon: <Network />,
        permission: FREIGHT_PERMS.fleet.view,
      },
      {
        label: "Locomotives",
        href: "/dashboard/locomotives",
        icon: <Train />,
        permission: FREIGHT_PERMS.fleet.view,
      },

      // {
      //   label: "Wagon types",
      //   href: "/dashboard/wagon-types",
      //   icon: <Boxes />,
      // },
      {
        label: "Wagons",
        href: "/dashboard/wagons",
        icon: <Truck />,
        permission: FREIGHT_PERMS.fleet.view,
      },
      {
        label: "Vehicles",
        href: "/dashboard/vehicles",
        icon: <Truck />,
        permission: FREIGHT_PERMS.fleet.view,
      },
      {
        label: "Drivers",
        href: "/dashboard/drivers",
        icon: <Users />,
        permission: FREIGHT_PERMS.fleet.view,
      },
      // {
      //   label: "Containers",
      //   href: "/dashboard/containers",
      //   icon: <Container />,
      // },
      // {
      //   label: "Cargoes",
      //   href: "/dashboard/cargoes",
      //   icon: <Package />,
      // },
    ],
  },
  {
    title: "Warehouse Management",
    items: [
      {
        label: "Warehouse Dashboard",
        href: "/dashboard/warehouse-dashboard",
        icon: <LayoutDashboard />,
      },
      {
        label: "Warehouses",
        href: "/dashboard/warehouses",
        icon: <Container />,
      },
      {
        label: "Inventory",
        href: "/dashboard/warehouse-inventory",
        icon: <Package />,
      },
      {
        label: "Arrival Queue",
        href: "/dashboard/arrival-queue",
        icon: <PackageOpen />,
      },
      {
        label: "Loading Queue",
        href: "/dashboard/loading-queue",
        icon: <Truck />,
      },
      {
        label: "Loaded Inventory",
        href: "/dashboard/loaded-inventory",
        icon: <PackageCheck />,
      },
      {
        label: "Dispatch Queue",
        href: "/dashboard/dispatch-queue",
        icon: <Send />,
      },
      {
        label: "Inventory Inquiry",
        href: "/dashboard/inventory-inquiry",
        icon: <Boxes />,
      },
      {
        label: "Allocation & Fees",
        href: "/dashboard/warehouse-rules",
        icon: <SlidersHorizontal />,
      },
      {
        label: "Fee Invoices",
        href: "/dashboard/warehouse-fee-invoices",
        icon: <Wallet />,
      },
    ],
  },
  {
    title: "Administration",
    items: [
      {
        label: "File settings",
        href: "/dashboard/file-settings",
        icon: <Paperclip />,
        permission: FREIGHT_PERMS.admin,
      },
      {
        label: "Dropdown settings",
        href: "/dashboard/dropdown-settings",
        icon: <Settings />,
        permission: FREIGHT_PERMS.admin,
      },
    ],
  },
  {
    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"),
      },
    ],
  },
];

/** Keep only items the user is permitted to see; drop now-empty sections. */
const filterSidebarByPermission = (
  sections: SidebarSection[],
  user: ReturnType<typeof useAuth>["user"],
): SidebarSection[] => {
  const itemAllowed = (item: SidebarItem): boolean => {
    if (!item.permission) return true;
    const keys = Array.isArray(item.permission)
      ? item.permission
      : [item.permission];
    return keys.some((key) => hasFreightPermission(user, key));
  };

  return sections
    .map((section) => ({
      ...section,
      items: section.items.filter(itemAllowed),
    }))
    .filter((section) => section.items.length > 0);
};

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

  const demoItems: SidebarItem[] = [];

  const sidebarSections = filterSidebarByPermission(
    buildSidebarSections(demoItems),
    user,
  );
  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="/um/*" element={<UserManagementHostPage />} />
        <Route path="*" element={<Navigate to="/auth" replace />} />
      </Routes>
    );
  }

  return (
    <Routes>
      <Route path="/um/*" element={<UserManagementHostPage />} />
      <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="profile" element={<MyProfilePage />} />

        <Route path="booking-requests" element={<BookingRequestsPage />} />
        <Route
          path="payments"
          element={
            <RequirePermission permission={FREIGHT_PERMS.bookings.view}>
              <PaymentsPage />
            </RequirePermission>
          }
        />
        <Route path="customers" element={<CustomersPage />} />
        <Route path="customers/:id" element={<CustomerDetailPage />} />
        <Route path="booking-requests/new" element={<NewBookingPage />} />
        <Route path="booking-requests/:id" element={<BookingRequestDetailPage />} />
        <Route
          path="booking-requests/:id/contract"
          element={<BookingContractPage />}
        />
        <Route
          path="clearance"
          element={
            <RequirePermission permission={FREIGHT_PERMS.bookings.reviewDocuments}>
              <GlClearancePage />
            </RequirePermission>
          }
        />
        <Route path="warehouses" element={<WarehouseListPage />} />
        <Route path="warehouses/:id" element={<WarehouseDetailPage />} />
        <Route path="warehouse-inventory" element={<WarehouseInventoryPage />} />
        <Route path="arrival-queue" element={<ArrivalQueuePage />} />
        <Route path="loading-queue" element={<LoadingQueuePage />} />
        <Route path="loaded-inventory" element={<LoadedInventoryPage />} />
        <Route path="dispatch-queue" element={<DispatchQueuePage />} />
        <Route path="inventory-inquiry" element={<InventoryInquiryPage />} />
        <Route path="warehouse-rules" element={<WarehouseRulesPage />} />
        <Route path="warehouse-fee-invoices" element={<WarehouseInvoicesPage />} />
        <Route path="warehouse-dashboard" element={<WarehouseDashboardPage />} />

          <Route
            path="operations/train-scheduling"
            element={<Navigate to="/dashboard/operations/train-scheduling-v2" replace />}
          />
          <Route
            path="operations/batch-board"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <BatchBoardPage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/first-mile"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <FirstMilePage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/last-mile"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <LastMilePage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/batch-board/:scheduleId"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <BatchScheduleDetailPage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/train-scheduling-v2"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <TrainScheduleV2ListPage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/train-scheduling-v2/:scheduleId"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <TrainScheduleV2DetailPage />
              </RequirePermission>
            }
          />
          <Route
            path="operations/train-scheduling-v2/:scheduleId/track"
            element={
              <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
                <TrainScheduleTrackPage />
              </RequirePermission>
            }
          />
          <Route
            path="routes"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <RoutesPage />
              </RequirePermission>
            }
          />
          <Route
            path="locomotives"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="trains"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="trains/:id"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <TrainDetailPage />
              </RequirePermission>
            }
          />
          <Route
            path="wagons"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="containers"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="cargoes"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="vehicles"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
          <Route
            path="drivers"
            element={
              <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
                <FleetResourcePage />
              </RequirePermission>
            }
          />
        <Route
          path="operations/train-scheduling"
          element={<Navigate to="/dashboard/operations/train-scheduling-v2" replace />}
        />
        <Route
          path="operations/batch-board"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <BatchBoardPage />
            </RequirePermission>
          }
        />
        <Route
          path="operations/batch-board/:scheduleId"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <BatchScheduleDetailPage />
            </RequirePermission>
          }
        />
        <Route
          path="operations/train-scheduling-v2"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <TrainScheduleV2ListPage />
            </RequirePermission>
          }
        />
        <Route
          path="operations/train-scheduling-v2/:scheduleId"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <TrainScheduleV2DetailPage />
            </RequirePermission>
          }
        />
        <Route
          path="operations/train-scheduling-v2/:scheduleId/track"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <TrainScheduleTrackPage />
            </RequirePermission>
          }
        />
        <Route
          path="routes"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <RoutesPage />
            </RequirePermission>
          }
        />
        <Route
          path="locomotives"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <FleetResourcePage />
            </RequirePermission>
          }
        />
        <Route
          path="trains"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <FleetResourcePage />
            </RequirePermission>
          }
        />
        <Route
          path="trains/:id"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <TrainDetailPage />
            </RequirePermission>
          }
        />
        <Route
          path="wagons"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <FleetResourcePage />
            </RequirePermission>
          }
        />
        <Route
          path="containers"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <FleetResourcePage />
            </RequirePermission>
          }
        />
        <Route
          path="cargoes"
          element={
            <RequirePermission permission={FREIGHT_PERMS.fleet.view}>
              <FleetResourcePage />
            </RequirePermission>
          }
        />

        {/* Legacy embedded user management routes */}
        <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={
            <RequirePermission permission={FREIGHT_PERMS.admin}>
              <FileUploadSettingsPage />
            </RequirePermission>
          }
        />
        <Route
          path="dropdown-settings"
          element={
            <RequirePermission permission={FREIGHT_PERMS.admin}>
              <DropdownSettingsPage />
            </RequirePermission>
          }
        />

        <Route
          path="configuration"
          element={<Navigate to="/dashboard/configuration/cargo-types" replace />}
        />
        <Route
          path="configuration/train-scheduling-rules"
          element={
            <RequirePermission permission={FREIGHT_PERMS.trainScheduling.view}>
              <TrainSchedulingGlobalRulesPage />
            </RequirePermission>
          }
        />
        <Route path="configuration/cargo-types" element={<CargoTypesPage />} />
        <Route path="configuration/cargo-types/:id" element={<CargoTypesPage />} />
        <Route path="configuration/:resource" element={<RuleEngineResourcePage />} />

        <Route
          path="rules"
          element={<Navigate to="/dashboard/rules/priority-configs" 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="/um" replace />} />
        <Route path="org-structure/*" element={<Navigate to="/um" replace />} />
      </Route>

      <Route path="*" element={<Navigate to="/dashboard/overview" replace />} />
    </Routes>
  );
};

export default App;
