import {
  useNavigate,
  useLocation,
  Routes,
  Route,
  Navigate,
  Outlet,
} from "react-router-dom";
import { DashboardLayout, type SidebarItem } from "@edr/ui-common";
import {
  CalendarCheck,
  MapPin,
  Receipt,
  Home,
  Loader2,
  User,
  Settings,
} from "lucide-react";

import useAuth from "./hooks/useAuth";

import ProfilePage from "./pages/ProfilePage";
import SettingsPage from "./pages/SettingsPage";
import MyPortalPage from "./pages/MyPortalPage";
import EDRFreightLandingPage from "./pages/EDRFreightLandingPage";
import SignupPage from "./pages/accounts/SignupPage";
import OnboardingPage from "./pages/accounts/OnboardingPage";
import VerificationOtpPage from "./pages/accounts/VerificationOtpPage";
import SetPasswordPage from "./pages/accounts/SetPasswordPage";
import LoginPage from "./pages/accounts/LoginPage";
import MyBookings from "./pages/bookings/MyBookings";
import BookingContractPage from "./pages/bookings/BookingContractPage";
import BookingDetailPage from "./pages/bookings/BookingDetailPage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import EditBookingPage from "./pages/bookings/EditBookingPage";
import CheckPaymentPage from "./pages/payments/CheckPaymentPage";
import TrackingPage from "./pages/tracking/TrackingPage";
import BillingPage from "./pages/billing/BillingPage";
import { useEffect } from "react";

const sidebarItems: SidebarItem[] = [
  { label: "Home", href: "/portal", icon: <Home /> },
  { label: "My Bookings", href: "/bookings", icon: <CalendarCheck /> },
  { label: "Tracking", href: "/tracking", icon: <MapPin /> },
  { label: "Billing", href: "/billing", icon: <Receipt /> },
  { label: "Profile", href: "/profile", icon: <User /> },
  { label: "Settings", href: "/settings", icon: <Settings /> },
];

const App = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, isPending, logout, customer, customerQuery } = useAuth();

  useEffect(() => {
    if (isPending || customerQuery.isPending) return;
    const isInProtectedRoutes = sidebarItems.find((item) =>
      location.pathname.startsWith(item.href),
    );
    console.log({ isInProtectedRoutes, location });
    if (!user) {
      if (isInProtectedRoutes) return navigate("/login");
      return;
    }

    if (user && location.pathname === "/") navigate("/portal");
    else if (!customer && !!isInProtectedRoutes) navigate("/onboarding");
  }, [user, location, customer]);

  if (isPending) {
    return (
      <div className="flex items-center justify-center h-screen">
        <Loader2 className="animate-spin text-primary" />
      </div>
    );
  }

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

  return (
    <Routes>
      <Route>
        <Route index element={<EDRFreightLandingPage />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/signup" element={<SignupPage />} />
        <Route path="/otp" element={<VerificationOtpPage />} />
        <Route path="/set-password" element={<SetPasswordPage />} />
        <Route path="/onboarding" element={<OnboardingPage />} />
        <Route
          path="/booking/check-status/:orderId"
          element={<CheckPaymentPage />}
        />
      </Route>
      <Route
        element={
          <DashboardLayout
            title="EDR Freight"
            sidebarItems={sidebarItems}
            activeHref={location.pathname}
            onNavigate={navigate}
            enableThemeToggle
            userName={displayName}
            userEmail={userEmail}
            onLogout={logout}
          >
            <Outlet />
          </DashboardLayout>
        }
      >
        <Route path="/portal" element={<MyPortalPage />} />
        <Route path="/bookings" element={<MyBookings />} />
        <Route path="/bookings/new" element={<NewBookingPage />} />
        <Route path="/bookings/:id/edit" element={<EditBookingPage />} />
        <Route path="/bookings/:id" element={<BookingDetailPage />} />
        <Route
          path="/bookings/:id/contract"
          element={<BookingContractPage />}
        />
        <Route path="/tracking" element={<TrackingPage />} />
        <Route path="/billing" element={<BillingPage />} />
        <Route path="/profile" element={<ProfilePage />} />
        <Route path="/settings" element={<SettingsPage />} />
      </Route>
      {/* <Route path="*" element={<Navigate to="/" replace />} /> */}
    </Routes>
  );
};

export default App;
