
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import Layout from '@/components/layout/Layout';
import AppNavigation from '@/components/layout/Sidebar';
import { ReleaseNotesDialog } from '@/components/ReleaseNotesDialog';
import LoginPage from '@/pages/LoginPage';
import AdminPage from '@/pages/AdminPage';
import TrackerPage from '@/pages/TrackerPage';
import CalendarPage from '@/pages/CalendarPage';
import SummaryPage from '@/pages/SummaryPage';
import BillsPage from '@/pages/BillsPage';
import CategoriesPage from '@/pages/CategoriesPage';
import SettingsPage from '@/pages/SettingsPage';
import StatusPage from '@/pages/StatusPage';
import AnalyticsPage from '@/pages/AnalyticsPage';
import ReleaseNotesPage from '@/pages/ReleaseNotesPage';
import AboutPage from '@/pages/AboutPage';
import DataPage from '@/pages/DataPage';
import ProfilePage from '@/pages/ProfilePage';
import ErrorBoundary from '@/components/ErrorBoundary';

function RequireAuth({ children, role }) {
  const { user, singleUserMode } = useAuth();
  const location = useLocation();

  // Loading state
  if (user === undefined) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-background text-muted-foreground text-sm">
        Loading...
      </div>
    );
  }

  // Single-user mode bypass
  if (singleUserMode && role === 'user') return children;

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

  const roleAllowed = !role || user.role === role || (role === 'user' && user.role === 'admin');

  if (role === 'user' && user.is_default_admin) {
    return <Navigate to="/admin" replace />;
  }

  // Role mismatch
  if (!roleAllowed) {
    return <Navigate to={user.role === 'admin' ? '/admin' : '/'} replace />;
  }

  return children;
}

function AdminShell({ children }) {
  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,oklch(var(--primary)/0.10),transparent_34rem),linear-gradient(180deg,oklch(var(--background)),oklch(var(--muted)/0.28))] text-foreground">
      <AppNavigation adminMode />
      <main className="mx-auto max-w-5xl px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
        {children}
      </main>
    </div>
  );
}

export default function App() {
  const { user } = useAuth();

  return (
    <>
      {/* Release notes (only for user role) */}
      {user?.role === 'user' && <ReleaseNotesDialog />}

      <Routes>
        <Route path="/login" element={<ErrorBoundary><LoginPage /></ErrorBoundary>} />
        <Route path="/about" element={<ErrorBoundary><AboutPage /></ErrorBoundary>} />
        <Route path="/release-notes" element={<ErrorBoundary><ReleaseNotesPage /></ErrorBoundary>} />

        <Route
          path="/admin"
          element={
            <RequireAuth role="admin">
              <ErrorBoundary>
                <AdminPage />
              </ErrorBoundary>
            </RequireAuth>
          }
        />
        <Route
          path="/admin/about"
          element={
            <RequireAuth role="admin">
              <ErrorBoundary>
                <AdminShell>
                  <AboutPage admin />
                </AdminShell>
              </ErrorBoundary>
            </RequireAuth>
          }
        />
        <Route
          path="/admin/status"
          element={
            <RequireAuth role="admin">
              <ErrorBoundary>
                <AdminShell>
                  <StatusPage />
                </AdminShell>
              </ErrorBoundary>
            </RequireAuth>
          }
        />
        <Route
          path="/status"
          element={
            <RequireAuth role="admin">
              <Navigate to="/admin/status" replace />
            </RequireAuth>
          }
        />

        <Route
          element={
            <RequireAuth role="user">
              <Layout />
            </RequireAuth>
          }
        >
          <Route index element={<ErrorBoundary><TrackerPage /></ErrorBoundary>} />
          <Route path="calendar" element={<ErrorBoundary><CalendarPage /></ErrorBoundary>} />
          <Route path="summary" element={<ErrorBoundary><SummaryPage /></ErrorBoundary>} />
          <Route path="bills" element={<ErrorBoundary><BillsPage /></ErrorBoundary>} />
          <Route path="categories" element={<ErrorBoundary><CategoriesPage /></ErrorBoundary>} />
          <Route path="analytics" element={<ErrorBoundary><AnalyticsPage /></ErrorBoundary>} />
          <Route path="settings" element={<ErrorBoundary><SettingsPage /></ErrorBoundary>} />
          <Route path="data" element={<ErrorBoundary><DataPage /></ErrorBoundary>} />
          <Route path="profile" element={<ErrorBoundary><ProfilePage /></ErrorBoundary>} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Route>
      </Routes>
    </>
  );
}
