import { Routes, Route, Navigate, useNavigate, useLocation } from "react-router-dom";
import { useEffect, useState } from "react";
import Layout from "./components/Layout";
import LoginPage from "./pages/LoginPage";
import DashboardPage from "./pages/DashboardPage";
import CommitteesPage from "./pages/CommitteesPage";
import UsersPage from "./pages/UsersPage";
import CasesPage from "./pages/CasesPage";
import DeadlinesPage from "./pages/DeadlinesPage";
import MeetingsPage from "./pages/MeetingsPage";
import AgendaItemsPage from "./pages/AgendaItemsPage";
import DecisionsPage from "./pages/DecisionsPage";
import TasksPage from "./pages/TasksPage";
import DocumentsPage from "./pages/DocumentsPage";
import CommentsPage from "./pages/CommentsPage";
import TemplatesPage from "./pages/TemplatesPage";
import NotificationsPage from "./pages/NotificationsPage";
import SecurityPage from "./pages/SecurityPage";
import AuditPage from "./pages/AuditPage";
import CalendarPage from "./pages/CalendarPage";
import ReportsPage from "./pages/ReportsPage";
import FinancePage from "./pages/FinancePage";
import FinanceTaxCodesPage from "./pages/FinanceTaxCodesPage";
import DepartmentsPage from "./pages/DepartmentsPage";
import DocumentCategoriesPage from "./pages/DocumentCategoriesPage";
import PublicDocumentsPage from "./pages/PublicDocumentsPage";
import PublicDocumentsAdminPage from "./pages/PublicDocumentsAdminPage";
import PermissionsPage from "./pages/PermissionsPage";
import KummerkastenPage from "./pages/KummerkastenPage";
import KummerkastenAdminPage from "./pages/KummerkastenAdminPage";
import { logoutLocal } from "./lib/auth";
import { api, setAccessToken } from "./lib/api";
import { canViewPath } from "./lib/access";

function ForbiddenPage() {
  return <div className="alert error">Keine Berechtigung für diese Seite.</div>;
}

function RequirePage({ user, path, children }) {
  return canViewPath(user, path) ? children : <ForbiddenPage />;
}

function page(user, path, component) {
  return <RequirePage user={user} path={path}>{component}</RequirePage>;
}

export default function App() {
  const [user, setUser] = useState(() => {
    const raw = localStorage.getItem("br_user");
    return raw ? JSON.parse(raw) : null;
  });
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    if (!user) return;
    let cancelled = false;
    api.get("/permissions/access")
      .then((access) => {
        if (cancelled) return;
        const updatedUser = { ...user, ...access };
        setUser(updatedUser);
        localStorage.setItem("br_user", JSON.stringify(updatedUser));
      })
      .catch(() => undefined);
    return () => { cancelled = true; };
  }, [user?.id]);

  if (location.pathname === "/kummerkasten" || location.pathname === "/public-documents") {
    return (
      <Routes>
        <Route path="/kummerkasten" element={<KummerkastenPage />} />
        <Route path="/public-documents" element={<PublicDocumentsPage />} />
        <Route path="*" element={<Navigate to={location.pathname === "/public-documents" ? "/public-documents" : "/kummerkasten"} replace />} />
      </Routes>
    );
  }

  if (!user) {
    return <LoginPage onLogin={(u) => { setUser(u); navigate("/"); }} />;
  }

  setAccessToken(localStorage.getItem("br_access_token") || window.__br_access_token || "");

  function handleLogout() {
    logoutLocal();
    setUser(null);
    navigate("/");
  }

  return (
    <Layout user={user} onLogout={handleLogout}>
      <Routes>
        <Route path="/" element={page(user, "/", <DashboardPage />)} />
        <Route path="/committees" element={page(user, "/committees", <CommitteesPage />)} />
        <Route path="/users" element={page(user, "/users", <UsersPage />)} />
        <Route path="/cases" element={page(user, "/cases", <CasesPage />)} />
        <Route path="/deadlines" element={page(user, "/deadlines", <DeadlinesPage />)} />
        <Route path="/meetings" element={page(user, "/meetings", <MeetingsPage />)} />
        <Route path="/agenda-items" element={page(user, "/agenda-items", <AgendaItemsPage />)} />
        <Route path="/decisions" element={page(user, "/decisions", <DecisionsPage />)} />
        <Route path="/tasks" element={page(user, "/tasks", <TasksPage />)} />
        <Route path="/calendar" element={page(user, "/calendar", <CalendarPage />)} />
        <Route path="/documents" element={page(user, "/documents", <DocumentsPage />)} />
        <Route path="/comments" element={page(user, "/comments", <CommentsPage />)} />
        <Route path="/reports" element={page(user, "/reports", <ReportsPage />)} />
        <Route path="/finance" element={page(user, "/finance", <FinancePage />)} />
        <Route path="/finance-tax-codes" element={page(user, "/finance-tax-codes", <FinanceTaxCodesPage />)} />
        <Route path="/departments" element={page(user, "/departments", <DepartmentsPage />)} />
        <Route path="/document-categories" element={page(user, "/document-categories", <DocumentCategoriesPage />)} />
        <Route path="/public-documents-admin" element={page(user, "/public-documents-admin", <PublicDocumentsAdminPage />)} />
        <Route path="/templates" element={page(user, "/templates", <TemplatesPage />)} />
        <Route path="/formular-editor" element={<Navigate to="/templates" replace />} />
        <Route path="/form-editor" element={<Navigate to="/templates" replace />} />
        <Route path="/notifications" element={page(user, "/notifications", <NotificationsPage />)} />
        <Route path="/permissions" element={page(user, "/permissions", <PermissionsPage />)} />
        <Route path="/kummerkasten-admin" element={page(user, "/kummerkasten-admin", <KummerkastenAdminPage />)} />
        <Route path="/security" element={page(user, "/security", <SecurityPage />)} />
        <Route path="/audit" element={page(user, "/audit", <AuditPage />)} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Layout>
  );
}
