import {
  useNavigate,
  useLocation,
  Routes,
  Route,
  Navigate,
} from "react-router-dom";
import { DashboardLayout, type SidebarItem } from "@edr/ui-common";
import {
  LayoutDashboard,
  Users,
  CalendarCheck,
  Package,
  MapPin,
  Train,
  Receipt,
  FileText,
  Settings,
  UserCircle,
  FileUp,
  MapPinned,
} from "lucide-react";

import BookingsPage from "./pages/bookings/BookingsPage";
import BookingDetailPage from "./pages/bookings/BookingDetailPage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import ConsignmentsPage from "./pages/consignments/ConsignmentsPage";
import ConsignmentDetailPage from "./pages/consignments/ConsignmentDetailPage";
import TrackingPage from "./pages/tracking/TrackingPage";
import BillingPage from "./pages/billing/BillingPage";
import TrainsPage from "./pages/trains/TrainsPage";
import DashboardPage from "./pages/dashboard/DashboardPage";
import {
  IamLoginPage,
  LoadingScreen,
  useAuth,
  useAuthUser,
} from "@tria-plc/iamui-common";
import CustomersPage from "./pages/customers/CustomersPage";
import CustomerDetailPage from "./pages/customers/CustomerDetailPage";
import NewCustomerPage from "./pages/customers/NewCustomerPage";
import DocumentsPage from "./pages/documents/DocumentsPage";
import DropdownSettingsPage from "./pages/admin/DropdownSettingsPage";
import FileUploadSettingsPage from "./pages/admin/FileUploadSettingsPage";
import MyPortalPage from "./pages/portal/MyPortalPage";
import Station from "./components/stations/Station";

const sidebarItems: SidebarItem[] = [
  { label: "My Portal", href: "/portal", icon: <UserCircle /> },
  { label: "Dashboard", href: "/", icon: <LayoutDashboard /> },
  { label: "Customers", href: "/customers", icon: <Users /> },
  { label: "Bookings", href: "/bookings", icon: <CalendarCheck /> },
  { label: "Consignments", href: "/consignments", icon: <Package /> },
  { label: "Tracking", href: "/tracking", icon: <MapPin /> },
  { label: "Stations", href: "/stations", icon: <MapPinned /> },
  { label: "Trains", href: "/trains", icon: <Train /> },
  { label: "Billing", href: "/billing", icon: <Receipt /> },
  { label: "Documents", href: "/documents", icon: <FileText /> },
  { label: "Dropdown Settings", href: "/admin/dropdowns", icon: <Settings /> },
  {
    label: "File Upload Settings",
    href: "/admin/file-uploads",
    icon: <FileUp />,
  },
];

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

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

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

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

  const handleLogout = () => {
    logout();
    [
      "auth-token",
      "refresh-token",
      "auth-user",
      "current-position-id",
      "selected-position-id",
    ].forEach((name) => {
      document.cookie = `${name}=; Max-Age=0; path=/`;
    });
    localStorage.clear();
    window.location.replace("/auth");
  };

  return (
    <DashboardLayout
      title="EDR Freight"
      sidebarItems={sidebarItems}
      activeHref={location.pathname}
      onNavigate={navigate}
      enableThemeToggle
      userName={displayName}
      userEmail={userEmail}
      onLogout={handleLogout}
    >
      <Routes>
        <Route path="/" element={<DashboardPage />} />
        <Route path="/portal" element={<MyPortalPage />} />
        <Route path="/bookings" element={<BookingsPage />} />
        <Route path="/customers" element={<CustomersPage />} />
        <Route path="/customers/:id" element={<CustomerDetailPage />} />
        <Route path="/new-customer" element={<NewCustomerPage />} />
        <Route path="/bookings/new" element={<NewBookingPage />} />
        <Route path="/bookings/:id" element={<BookingDetailPage />} />
        <Route path="/consignments" element={<ConsignmentsPage />} />
        <Route path="/consignments/:id" element={<ConsignmentDetailPage />} />
        <Route path="/tracking" element={<TrackingPage />} />
        <Route path="/stations" element={<Station />} />
        <Route path="/trains" element={<TrainsPage />} />
        <Route path="/billing" element={<BillingPage />} />
        <Route path="/documents" element={<DocumentsPage />} />
        <Route
          path="/admin/dropdowns"
          element={<DropdownSettingsPage />}
        />
        <Route
          path="/admin/file-uploads"
          element={<FileUploadSettingsPage />}
        />
        <Route path="/user-management" element={<Navigate to="/" replace />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </DashboardLayout>
  );
};

export default App;
