import { useLocation, useNavigate, Routes, Route } from 'react-router-dom';
import { AuthProvider, useAuth, ProtectedRoute } from '@persona-community-5/auth';
import { DashboardShell, Sidebar, Header, type NavItem } from '@persona-community-5/layout';
import {
  Home,
  Loader2,
} from '@persona-community-5/ui';
import { LoginPage } from './pages/LoginPage';
import { CommunityPage } from './pages/CommunityPage';
import { PersonaDetailPage } from './pages/PersonaDetailPage';

const navItems: NavItem[] = [
  { label: 'Community', href: '/', icon: Home },
];

function LoadingScreen() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--surface-100)]">
      <div className="flex flex-col items-center gap-4">
        <Loader2 className="h-8 w-8 animate-spin text-[var(--accent)]" />
        <p className="text-sm text-[var(--text-muted)]">Loading...</p>
      </div>
    </div>
  );
}

function AppLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout } = useAuth();

  const itemsWithActive = navItems.map((item) => ({
    ...item,
    active: location.pathname === item.href,
  }));

  const pageTitle = location.pathname.startsWith('/personas/') ? 'Persona' : 'Community';

  return (
    <DashboardShell
      sidebar={
        <Sidebar
          logo={
            <span className="font-semibold text-lg">Persona Community</span>
          }
          items={itemsWithActive}
          onNavigate={(href) => navigate(href)}
          footer={
            <div className="flex flex-col gap-2">
              <span className="text-sm text-[var(--text-muted)] truncate">
                {user?.email || ''}
              </span>
              <button
                type="button"
                onClick={async () => { await logout(); navigate('/login'); }}
                className="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-left"
              >
                Sign out
              </button>
            </div>
          }
        />
      }
      header={
        <Header title={pageTitle} />
      }
    >
      <Routes>
        <Route path="/" element={<CommunityPage />} />
        <Route path="/personas/:id" element={<PersonaDetailPage />} />
      </Routes>
    </DashboardShell>
  );
}

function AppRoutes() {
  const location = useLocation();
  const navigate = useNavigate();

  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/*"
        element={
          <ProtectedRoute
            redirectTo="/login"
            onRedirect={(path) => {
              navigate(path, { state: { from: location.pathname }, replace: true });
            }}
            fallback={<LoadingScreen />}
          >
            <AppLayout />
          </ProtectedRoute>
        }
      />
    </Routes>
  );
}

function App() {
  const apiBaseUrl = import.meta.env.VITE_API_URL || '';

  return (
    <AuthProvider authBaseUrl={`${apiBaseUrl}/api/persona-api`}>
      <AppRoutes />
    </AuthProvider>
  );
}

export default App;
