import { useEffect, useState } from "react";
import type { Session } from "./api/types";
import { api } from "./api/client";
import { isPrivateRoute } from "./auth/routing";
import { AppShell } from "./layout/AppShell";
import { AdminAutomationPage } from "./pages/AdminAutomationPage";
import { AdminPage } from "./pages/AdminPage";
import { BookPage } from "./pages/BookPage";
import { HomePage } from "./pages/HomePage";
import { LibraryPage } from "./pages/LibraryPage";
import { LoginPage } from "./pages/LoginPage";
import { ProfilePage } from "./pages/ProfilePage";
import { ReaderPage } from "./pages/ReaderPage";
import { SearchPage } from "./pages/SearchPage";
import { SetupPage } from "./pages/SetupPage";
import { navigate, parseRoute, type Route } from "./router";

function renderRoute(route: Route, session: Session, refreshSession: () => Promise<void>) {
  if (route.name === "login") return <LoginPage onSessionChange={refreshSession} />;
  if (route.name === "setup") return <SetupPage />;

  const content =
    route.name === "home" ? (
      <HomePage />
    ) : route.name === "library" ? (
      <LibraryPage libraryId={route.libraryId} />
    ) : route.name === "book" ? (
      <BookPage bookId={route.bookId} />
    ) : route.name === "reader" ? (
      <ReaderPage bookId={route.bookId} />
    ) : route.name === "search" ? (
      <SearchPage />
    ) : route.name === "me" ? (
      <ProfilePage session={session} onSessionChange={refreshSession} />
    ) : route.name === "admin" && route.section === "automation" ? (
      <AdminAutomationPage />
    ) : (
      <AdminPage />
    );

  return <AppShell session={session}>{content}</AppShell>;
}

export function App() {
  const [route, setRoute] = useState(parseRoute());
  const [session, setSession] = useState<Session>({ user: null, degraded: false });
  const [sessionChecked, setSessionChecked] = useState(false);

  async function refreshSession() {
    setSession(await api.session());
    setSessionChecked(true);
  }

  useEffect(() => {
    refreshSession();
  }, []);

  useEffect(() => {
    const listener = () => setRoute(parseRoute());
    window.addEventListener("popstate", listener);
    return () => window.removeEventListener("popstate", listener);
  }, []);

  useEffect(() => {
    const listener = () => {
      setSession({ user: null, degraded: false });
      setSessionChecked(true);
      if (isPrivateRoute(parseRoute())) navigate("/login");
    };
    window.addEventListener("readabook:session-expired", listener);
    return () => window.removeEventListener("readabook:session-expired", listener);
  }, []);

  useEffect(() => {
    if (sessionChecked && !session.user && isPrivateRoute(route)) navigate("/login");
  }, [route, session.user, sessionChecked]);

  if (!sessionChecked && isPrivateRoute(route)) {
    return (
      <div className="auth-surface">
        <section className="auth-hero">
          <p>Cabinet de curiosites numerique</p>
          <h1>ReadaBook</h1>
          <span>Verification de session.</span>
        </section>
      </div>
    );
  }

  if (sessionChecked && !session.user && isPrivateRoute(route)) {
    return <LoginPage onSessionChange={refreshSession} />;
  }

  return renderRoute(route, session, refreshSession);
}
