import { AppLayout, type SidebarItem } from "@/components/AppLayout";
import {
  CalendarCheck,
  Home,
  Loader2,
  MapPin,
  Receipt,
  Settings,
  User,
} from "lucide-react";
import { useEffect, useRef } from "react";
import {
  Navigate,
  Outlet,
  Route,
  Routes,
  useLocation,
  useNavigate,
} from "react-router-dom";

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

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

function LogoutHandler() {
  const { logout } = useAuth();
  const navigate = useNavigate();
  const hasRun = useRef(false);

  useEffect(() => {
    if (hasRun.current) return;
    hasRun.current = true;
    logout().then(() => navigate("/login", { replace: true }));
  }, []);

  return <FullScreenSpinner />;
}

/** Blocks unauthenticated users; renders children only with a valid session. */
function RequireAuth() {
  const { isPending, isAuthenticated } = useAuth();
  const location = useLocation();

  if (isPending) return <FullScreenSpinner />;
  if (!isAuthenticated)
    return <Navigate to="/login" replace state={{ from: location }} />;
  return <Outlet />;
}

/**
 * Sends authenticated users without a company to onboarding.
 * Only redirects on a confirmed "no company" response — never on a
 * transient query error.
 */
function RequireCompany() {
  const { customerQuery } = useAuth();

  if (customerQuery.isPending) return <FullScreenSpinner />;
  return <Outlet />;
}

/** Keeps already-onboarded users out of the onboarding flow. */
function RequireNoCompany() {
  const { customerQuery } = useAuth();

  if (customerQuery.isPending) return <FullScreenSpinner />;
  if (customerQuery.data) return <Navigate to="/portal" replace />;
  return <Outlet />;
}

/** Keeps authenticated users off the login/signup pages. */
function RedirectIfAuthed() {
  const { isPending, isAuthenticated } = useAuth();

  if (isPending) return <FullScreenSpinner />;
  if (isAuthenticated) return <Navigate to="/portal" replace />;
  return <Outlet />;
}

/** Landing page for visitors; authenticated users go straight to the portal. */
function LandingRoute() {
  const { isPending, isAuthenticated } = useAuth();

  if (isPending) return <FullScreenSpinner />;
  if (isAuthenticated) return <Navigate to="/portal" replace />;
  return <EDRFreightLandingPage />;
}

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

const App = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user } = useAuth();

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

  return (
    <Routes>
      {/* Public routes */}
      <Route index element={<LandingRoute />} />
      <Route path="/logout" element={<LogoutHandler />} />
      <Route
        path="/booking/check-status/:orderId"
        element={<CheckPaymentPage />}
      />

      {/* Auth pages — inaccessible once logged in */}
      <Route element={<RedirectIfAuthed />}>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/signup" element={<SignupPage />} />
      </Route>

      {/* Signup-flow pages; reached while a session already exists */}
      <Route path="/otp" element={<VerificationOtpPage />} />
      <Route path="/set-password" element={<SetPasswordPage />} />

      <Route element={<RequireAuth />}>
        <Route element={<RequireNoCompany />}>
          <Route path="/onboarding" element={<OnboardingPage />} />
        </Route>

        <Route element={<RequireCompany />}>
          <Route
            element={
              <AppLayout
                title="EDR Freight"
                sidebarItems={sidebarItems}
                activeHref={location.pathname}
                onNavigate={navigate}
                enableThemeToggle
                userName={displayName}
                userEmail={userEmail}
              >
                <Outlet />
              </AppLayout>
            }
          >
            <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="/signature" element={<MySignaturePage />} />
            <Route path="/settings" element={<SettingsPage />} />
          </Route>
        </Route>
      </Route>

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

export default App;
