import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom";

import { AppShell } from "./components/AppShell";
import { AdminPage } from "./pages/AdminPage";
import { AccountPage } from "./pages/AccountPage";
import { ArchitecturePage } from "./pages/ArchitecturePage";
import { CloudDocumentsPage } from "./pages/CloudDocumentsPage";
import { DataDeletionPage } from "./pages/DataDeletionPage";
import { DashboardPage } from "./pages/DashboardPage";
import { FiscalDocumentsPage } from "./pages/FiscalDocumentsPage";
import { HomemadePage } from "./pages/HomemadePage";
import { InventoryPage } from "./pages/InventoryPage";
import { LandingPage } from "./pages/LandingPage";
import { LoginPage } from "./pages/LoginPage";
import { ModuleLaunchPage } from "./pages/ModuleLaunchPage";
import { NotFoundPage } from "./pages/NotFoundPage";
import { PrivacyPage } from "./pages/PrivacyPage";
import { TermsPage } from "./pages/TermsPage";
import { TimeclockPage } from "./pages/TimeclockPage";
import { canAccessTenantPath, describeTenantAccess, getTenantDefaultPath } from "./config/workspace";
import { usePortalSession } from "./context/PortalSessionContext";

function LoadingScreen() {
  return (
    <section className="portal-frame auth-shell">
      <div className="portal-background" />
      <main className="page-shell">
        <section className="panel narrow-panel stack-md">
          <p className="eyebrow">Accesso</p>
          <h2 className="page-title">Verifica sessione in corso</h2>
          <p className="muted-copy">Sto controllando il locale, l'utente e il database associato.</p>
        </section>
      </main>
    </section>
  );
}

function ProtectedLayout() {
  const { status } = usePortalSession();
  const location = useLocation();

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

  if (status !== "authenticated") {
    return <Navigate to="/login" replace state={{ from: location.pathname }} />;
  }

  return (
    <AppShell>
      <Outlet />
    </AppShell>
  );
}

function AccessDeniedScreen({ areaLabel }: { areaLabel: string }) {
  return (
    <section className="panel narrow-panel stack-md">
      <p className="eyebrow">Accesso non autorizzato</p>
      <h2 className="page-title">Questa funzione non e disponibile per il tuo account</h2>
      <p className="muted-copy">
        Non hai accesso a {areaLabel}. Se ti serve per il tuo lavoro, chiedi all&apos;amministratore del locale di
        abilitarti da <strong>Account</strong>.
      </p>
    </section>
  );
}

function TenantWorkspaceRoute() {
  const { currentUser, platformAdmin } = usePortalSession();
  const location = useLocation();

  if (currentUser?.role === "super_admin" && !platformAdmin?.is_impersonating) {
    return <Navigate to="/admin" replace />;
  }

  if (!canAccessTenantPath(currentUser?.role, currentUser?.permissions, location.pathname)) {
    return <AccessDeniedScreen areaLabel={describeTenantAccess(location.pathname)} />;
  }

  return <Outlet />;
}

function AdminWorkspaceRoute() {
  const { currentUser, platformAdmin } = usePortalSession();

  if (currentUser?.role !== "super_admin") {
    return <Navigate to="/home" replace />;
  }

  if (platformAdmin?.is_impersonating) {
    return <Navigate to="/home" replace />;
  }

  return <Outlet />;
}

function RootRoute() {
  const { currentUser, platformAdmin, status } = usePortalSession();

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

  if (status !== "authenticated") {
    return <LoginPage />;
  }

  return currentUser?.role === "super_admin" && !platformAdmin?.is_impersonating
    ? <Navigate to="/admin" replace />
    : <Navigate to={getTenantDefaultPath(currentUser?.role, currentUser?.permissions)} replace />;
}

function LoginRoute() {
  const { currentUser, platformAdmin, status } = usePortalSession();

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

  if (status !== "authenticated") {
    return <LoginPage />;
  }

  return currentUser?.role === "super_admin" && !platformAdmin?.is_impersonating
    ? <Navigate to="/admin" replace />
    : <Navigate to={getTenantDefaultPath(currentUser?.role, currentUser?.permissions)} replace />;
}

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<RootRoute />} />
      <Route path="/login" element={<LoginRoute />} />
      <Route path="/privacy" element={<PrivacyPage />} />
      <Route path="/terms" element={<TermsPage />} />
      <Route path="/data-deletion" element={<DataDeletionPage />} />
      <Route element={<ProtectedLayout />}>
        <Route element={<AdminWorkspaceRoute />}>
          <Route path="/admin" element={<AdminPage />} />
        </Route>
        <Route element={<TenantWorkspaceRoute />}>
          <Route path="/home" element={<LandingPage />} />
          <Route path="/dashboard" element={<DashboardPage />} />
          <Route path="/timeclock" element={<TimeclockPage />} />
          <Route path="/inventory" element={<InventoryPage />} />
          <Route path="/fiscal-documents" element={<FiscalDocumentsPage />} />
          <Route path="/documents" element={<CloudDocumentsPage />} />
          <Route path="/account" element={<AccountPage />} />
          <Route path="/homemade" element={<HomemadePage />} />
          <Route path="/modules/:moduleKey" element={<ModuleLaunchPage />} />
          <Route path="/architecture" element={<ArchitecturePage />} />
        </Route>
        <Route path="*" element={<NotFoundPage />} />
      </Route>
    </Routes>
  );
}
