import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from '@/features/auth/hooks/useAuth';
import { useAuthStore } from '@/features/auth/store/authStore';
import { TokenStorage } from '@/services/tokenStorage';
import { ProtectedRoute } from '@/components/auth/ProtectedRoute';
import { DashboardLayout } from '@/components/layout/DashboardLayout';

import { ErrorBoundary } from '@/components/ErrorBoundary';
import {
  LazyLogin,
  LazyRegister,
  LazyForgotPassword,
  LazyVerifyEmail,
  LazyResetPassword,
  LazyDashboard,
  LazyChat,
  LazyLibrary,
  LazyProfile,
  LazySettings,
  LazySessions,
  LazyNotFound,
  LazyServerError,
  LazyUserProfile,
  LazyRoles,
  LazyTrackDetail,
  LazyPlaylistRoutes,
  LazyMarketplace,
  LazySearch,
  LazyNotifications,
  LazyAnalytics,
  LazyWebhooks,
  LazyAdminDashboard,
  LazyDesignSystemDemo,
  LazySocial,
  LazyGear,
  LazyLive,
  LazyEducation,
  LazyQueue,
  LazyDeveloper,
} from '@/components/ui/LazyComponent';

// Composant wrapper pour les routes protégées avec DashboardLayout
function ProtectedLayoutRoute({ children }: { children: React.ReactNode }) {
  // On pourrait ajouter isLoading ici si on avait un état de chargement global
  return <DashboardLayout>{children}</DashboardLayout>;
}

// Composant pour les routes publiques
function PublicRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, user } = useAuth();
  const hasToken = !!TokenStorage.getAccessToken();
  const { isLoading } = useAuthStore();

  // Ne pas rediriger si on charge encore (pour éviter les redirections pendant le login)
  if (isLoading) {
    return null;
  }

  // Vérifier à la fois le store et le token pour éviter les problèmes de timing
  const isAuth = isAuthenticated || (hasToken && user);

  if (isAuth) {
    return <Navigate to="/dashboard" replace />;
  }

  return <>{children}</>;
}

export const AppRouter = () => (
  <Routes>
    {/* Routes publiques */}
    <Route
      path="/login"
      element={
        <PublicRoute>
          <ErrorBoundary>
            <LazyLogin />
          </ErrorBoundary>
        </PublicRoute>
      }
    />
    <Route
      path="/register"
      element={
        <PublicRoute>
          <ErrorBoundary>
            <LazyRegister />
          </ErrorBoundary>
        </PublicRoute>
      }
    />
    <Route
      path="/forgot-password"
      element={
        <PublicRoute>
          <ErrorBoundary>
            <LazyForgotPassword />
          </ErrorBoundary>
        </PublicRoute>
      }
    />
    <Route
      path="/verify-email"
      element={
        <PublicRoute>
          <ErrorBoundary>
            <LazyVerifyEmail />
          </ErrorBoundary>
        </PublicRoute>
      }
    />
    <Route
      path="/reset-password"
      element={
        <PublicRoute>
          <ErrorBoundary>
            <LazyResetPassword />
          </ErrorBoundary>
        </PublicRoute>
      }
    />

    {/* Design System Demo - Public route for testing */}
    <Route
      path="/design-system"
      element={
        <ErrorBoundary>
          <LazyDesignSystemDemo />
        </ErrorBoundary>
      }
    />

    {/* T0213: Public user profile page */}
    <Route
      path="/u/:username"
      element={
        <ErrorBoundary>
          <LazyUserProfile />
        </ErrorBoundary>
      }
    />

    {/* Routes protégées */}
    <Route
      path="/dashboard"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyDashboard />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/marketplace"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyMarketplace />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/chat"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyChat />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/library"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyLibrary />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/profile"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyProfile />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/settings"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazySettings />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/settings/sessions"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazySessions />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/admin/roles"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyRoles />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/tracks/:id"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyTrackDetail />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/playlists/*"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyPlaylistRoutes />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/search"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazySearch />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/notifications"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyNotifications />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/analytics"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyAnalytics />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/webhooks"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyWebhooks />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/admin"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyAdminDashboard />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/social"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazySocial />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/gear"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyGear />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/live"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyLive />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/education"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyEducation />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/queue"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyQueue />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />
    <Route
      path="/developer"
      element={
        <ProtectedRoute>
          <ProtectedLayoutRoute>
            <ErrorBoundary>
              <LazyDeveloper />
            </ErrorBoundary>
          </ProtectedLayoutRoute>
        </ProtectedRoute>
      }
    />

    {/* Routes d'erreur */}
    <Route
      path="/404"
      element={
        <ErrorBoundary>
          <LazyNotFound />
        </ErrorBoundary>
      }
    />
    <Route
      path="/500"
      element={
        <ErrorBoundary>
          <LazyServerError />
        </ErrorBoundary>
      }
    />

    {/* Routes par défaut */}
    <Route path="/" element={<Navigate to="/dashboard" replace />} />
    <Route path="*" element={<Navigate to="/404" replace />} />
  </Routes>
);
