import { lazy, Suspense, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { AnimatePresence } from 'framer-motion';
import { Navbar } from '@/components/layout/Navbar';
import { ActiveMatchBanner } from '@/components/layout/ActiveMatchBanner';
import { useAuthStore } from '@/stores/authStore';
import { profileAPI } from '@/api/client';
import { Loader2 } from 'lucide-react';

const Landing = lazy(() => import('@/pages/Landing'));
const Login = lazy(() => import('@/pages/Login'));
const Register = lazy(() => import('@/pages/Register'));
const Dashboard = lazy(() => import('@/pages/Dashboard'));
const Queue = lazy(() => import('@/pages/Queue'));
const MatchLive = lazy(() => import('@/pages/MatchLive'));
const MatchHistory = lazy(() => import('@/pages/MatchHistory'));
const MatchDetails = lazy(() => import('@/pages/MatchDetails'));
const Leaderboard = lazy(() => import('@/pages/Leaderboard'));
const Profile = lazy(() => import('@/pages/Profile'));
const PublicProfile = lazy(() => import('@/pages/PublicProfile'));
const Settings = lazy(() => import('@/pages/Settings'));
const Support = lazy(() => import('@/pages/Support'));
const TicketDetail = lazy(() => import('@/pages/TicketDetail'));
const NotFound = lazy(() => import('@/pages/NotFound'));

const AdminLayout = lazy(() => import('@/pages/admin/AdminLayout'));
const SystemOverview = lazy(() => import('@/pages/admin/SystemOverview'));
const SystemConfig = lazy(() => import('@/pages/admin/SystemConfig'));
const UserManagement = lazy(() => import('@/pages/admin/UserManagement'));
const UserDetail = lazy(() => import('@/pages/admin/UserDetail'));
const EloConfig = lazy(() => import('@/pages/admin/EloConfig'));
const AuditLog = lazy(() => import('@/pages/admin/AuditLog'));
const PlatformStats = lazy(() => import('@/pages/admin/PlatformStats'));
const TicketQueue = lazy(() => import('@/pages/admin/TicketQueue'));
const TicketManage = lazy(() => import('@/pages/admin/TicketManage'));
const UserLookup = lazy(() => import('@/pages/admin/UserLookup'));
const MatchAdmin = lazy(() => import('@/pages/admin/MatchAdmin'));

function LoadingSpinner() {
  return (
    <div className="min-h-screen bg-bg-base flex items-center justify-center">
      <Loader2 className="w-8 h-8 text-amber-500 animate-spin" />
    </div>
  );
}

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const isLoading = useAuthStore((s) => s.isLoading);

  if (isLoading) return <LoadingSpinner />;
  if (!isAuthenticated) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

function AuthLayout({ children }: { children: React.ReactNode }) {
  return (
    <div className="min-h-screen bg-bg-base">
      <Navbar />
      <ActiveMatchBanner />
      <main>{children}</main>
    </div>
  );
}

function AuthBootstrap({ children }: { children: React.ReactNode }) {
  const token = useAuthStore((s) => s.token);
  const user = useAuthStore((s) => s.user);
  const isLoading = useAuthStore((s) => s.isLoading);

  useEffect(() => {
    if (token && !user) {
      profileAPI
        .me()
        .then(({ data }) => {
          useAuthStore.getState().setUser(data);
          useAuthStore.getState().setLoading(false);
        })
        .catch(() => {
          useAuthStore.getState().logout();
        });
    } else if (!token) {
      useAuthStore.getState().setLoading(false);
    }
  }, [token, user]);

  if (isLoading) return <LoadingSpinner />;
  return <>{children}</>;
}

function AnimatedRoutes() {
  const location = useLocation();

  return (
    <AnimatePresence mode="wait">
      <Suspense fallback={<LoadingSpinner />} key={location.pathname}>
        <Routes location={location}>
          <Route path="/" element={<Landing />} />
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />

          <Route path="/dashboard" element={<ProtectedRoute><AuthLayout><Dashboard /></AuthLayout></ProtectedRoute>} />
          <Route path="/queue" element={<ProtectedRoute><AuthLayout><Queue /></AuthLayout></ProtectedRoute>} />
          <Route path="/match/:id" element={<ProtectedRoute><AuthLayout><MatchLive /></AuthLayout></ProtectedRoute>} />
          <Route path="/match/:id/details" element={<ProtectedRoute><AuthLayout><MatchDetails /></AuthLayout></ProtectedRoute>} />
          <Route path="/history" element={<ProtectedRoute><AuthLayout><MatchHistory /></AuthLayout></ProtectedRoute>} />
          <Route path="/leaderboard" element={<ProtectedRoute><AuthLayout><Leaderboard /></AuthLayout></ProtectedRoute>} />
          <Route path="/profile" element={<ProtectedRoute><AuthLayout><Profile /></AuthLayout></ProtectedRoute>} />
          <Route path="/player/:username" element={<ProtectedRoute><AuthLayout><PublicProfile /></AuthLayout></ProtectedRoute>} />
          <Route path="/settings" element={<ProtectedRoute><AuthLayout><Settings /></AuthLayout></ProtectedRoute>} />
          <Route path="/support" element={<ProtectedRoute><AuthLayout><Support /></AuthLayout></ProtectedRoute>} />
          <Route path="/support/:id" element={<ProtectedRoute><AuthLayout><TicketDetail /></AuthLayout></ProtectedRoute>} />

          <Route path="/admin" element={<ProtectedRoute><AuthLayout><AdminLayout /></AuthLayout></ProtectedRoute>}>
            <Route index element={<Navigate to="/admin/tickets" replace />} />
            <Route path="system" element={<SystemOverview />} />
            <Route path="config" element={<SystemConfig />} />
            <Route path="users" element={<UserManagement />} />
            <Route path="users/lookup" element={<UserLookup />} />
            <Route path="users/:id" element={<UserDetail />} />
            <Route path="elo" element={<EloConfig />} />
            <Route path="audit" element={<AuditLog />} />
            <Route path="stats" element={<PlatformStats />} />
            <Route path="tickets" element={<TicketQueue />} />
            <Route path="tickets/:id" element={<TicketManage />} />
            <Route path="matches" element={<MatchAdmin />} />
          </Route>

          <Route path="*" element={<AuthLayout><NotFound /></AuthLayout>} />
        </Routes>
      </Suspense>
    </AnimatePresence>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthBootstrap>
        <AnimatedRoutes />
      </AuthBootstrap>
    </BrowserRouter>
  );
}
