import { Routes, Route, Navigate } from 'react-router';
import { AppShell } from '../components/layout/AppShell';
import { ProtectedRoute } from './ProtectedRoute';
import { ConnectPage } from '../features/connect/ConnectPage';
import { HomePage } from '../features/home/HomePage';
import { LibraryPage } from '../features/library/LibraryPage';
import { AlbumDetailPage } from '../features/album-detail/AlbumDetailPage';
import { PlaylistDetailPage } from '../features/playlist-detail/PlaylistDetailPage';
import { lazy, Suspense } from 'react';
import { LoadingSkeleton } from '../components/common/LoadingSkeleton';

const SearchDownloadPage = lazy(() => import('../features/search-download/SearchDownloadPage').then((m) => ({ default: m.SearchDownloadPage })));
const DownloadsManagerPage = lazy(() => import('../features/downloads-manager/DownloadsManagerPage').then((m) => ({ default: m.DownloadsManagerPage })));
const StoragePage = lazy(() => import('../features/storage/StoragePage').then((m) => ({ default: m.StoragePage })));
const AdminPage = lazy(() => import('../features/admin/AdminPage').then((m) => ({ default: m.AdminPage })));
const SettingsPage = lazy(() => import('../features/settings/SettingsPage').then((m) => ({ default: m.SettingsPage })));

const Fallback = () => <div style={{ padding: '2rem' }}><LoadingSkeleton /></div>;

export function AppRoutes() {
  return (
    <Routes>
      <Route path="/connect" element={<ConnectPage />} />
      <Route
        element={
          <ProtectedRoute>
            <AppShell />
          </ProtectedRoute>
        }
      >
        <Route index element={<HomePage />} />
        <Route path="/library" element={<LibraryPage />} />
        <Route path="/library/albums/:albumId" element={<AlbumDetailPage />} />
        <Route path="/library/playlists/:playlistId" element={<PlaylistDetailPage />} />
        <Route path="/search" element={<Suspense fallback={<Fallback />}><SearchDownloadPage /></Suspense>} />
        <Route path="/downloads" element={<Suspense fallback={<Fallback />}><DownloadsManagerPage /></Suspense>} />
        <Route path="/storage" element={<Suspense fallback={<Fallback />}><StoragePage /></Suspense>} />
        <Route path="/settings" element={<Suspense fallback={<Fallback />}><SettingsPage /></Suspense>} />
        <Route
          path="/admin/*"
          element={
            <ProtectedRoute requireAdmin>
              <Suspense fallback={<Fallback />}><AdminPage /></Suspense>
            </ProtectedRoute>
          }
        />
      </Route>
      <Route path="*" element={<Navigate to="/library" replace />} />
    </Routes>
  );
}
