import {
  createRootRoute,
  Outlet,
  useNavigate,
  useSearch,
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import { Toaster } from "sonner";
import Navbar from "../components/navbar/NavBar";
import NotFound from "../components/NotFound";
import RootError from "../components/RootError";
import { AuthModal } from "../components/auth/AuthModal";
import { AuthModalSearchSchema } from "@lila/shared";

const RootLayout = () => {
  const navigate = useNavigate();
  const { modal, redirect } = useSearch({ from: "__root__" });

  const handleClose = () => {
    void navigate({ to: "/", search: {} });
  };

  const handleSuccess = () => {
    void navigate({ to: (redirect as string) ?? "/", search: {} });
  };

  return (
    <>
      <Navbar />
      <main className="max-w-5xl mx-auto px-6 py-8">
        <Outlet />
      </main>
      {modal === "auth" && (
        <AuthModal onClose={handleClose} onSuccess={handleSuccess} />
      )}
      <Toaster richColors position="top-center" />
      <TanStackRouterDevtools />
    </>
  );
};

export const Route = createRootRoute({
  component: RootLayout,
  notFoundComponent: NotFound,
  errorComponent: RootError,
  validateSearch: AuthModalSearchSchema,
});
