import React, { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import AuthRoute from '../components/auth/AuthRoute';
import GuestRoute from '../components/auth/GuestRoute';
import AdminRoute from '../components/auth/AdminRoute';
import AdminLayout from '../components/admin/AdminLayout';
import LoadingSpinner from '../components/common/LoadingSpinner';
import TelegramAuth from '../components/TelegramAuth';

// Ленивая загрузка страниц
const HomePage = lazy(() => import('../pages/HomePage'));
const CatalogPage = lazy(() => import('../pages/CatalogPage'));
const MediaOverviewPage = lazy(() => import('../pages/MediaOverviewPage'));
const ProfilePage = lazy(() => import('../pages/ProfilePage'));
const RatingPage = lazy(() => import('../pages/RatingPage'));
const LoginPage = lazy(() => import('../pages/LoginPage'));
const RegisterPage = lazy(() => import('../pages/RegisterPage'));
const ForgotPasswordPage = lazy(() => import('../pages/ForgotPasswordPage'));
const SupportPage = lazy(() => import('../pages/SupportPage'));
const NotFoundPage = lazy(() => import('../pages/NotFoundPage'));

// Админские страницы
const AdminDashboard = lazy(() => import('../pages/admin/AdminDashboard'));
const AdminMediaPage = lazy(() => import('../pages/admin/AdminMediaPage'));
const AdminUsersPage = lazy(() => import('../pages/admin/AdminUsersPage'));
const AdminSeasonsPage = lazy(() => import('../pages/admin/AdminSeasonsPage'));
const AdminAchievementsPage = lazy(() => import('../pages/admin/AdminAchievementsPage'));
const AdminSupportPage = lazy(() => import('../pages/admin/AdminSupportPage'));
const AdminSuggestionsPage = lazy(() => import('../pages/admin/AdminSuggestionsPage'));

// Легальные страницы
const PrivacyPolicyPage = lazy(() => import('../pages/legal/PrivacyPolicyPage'));
const TermsOfServicePage = lazy(() => import('../pages/legal/TermsOfServicePage'));
const UserAgreementPage = lazy(() => import('../pages/legal/UserAgreementPage'));

// Компонент для обработки ошибок
const ErrorBoundary = ({ children }) => {
  const [hasError, setHasError] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const handleError = (error) => {
      setHasError(true);
      setError(error);
      // Здесь можно добавить логирование ошибки
      console.error('Route Error:', error);
    };

    window.addEventListener('error', handleError);
    return () => window.removeEventListener('error', handleError);
  }, []);

  if (hasError) {
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
          <h2 className="text-xl font-bold mb-2">Произошла ошибка</h2>
          <p>{error?.message || 'Неизвестная ошибка'}</p>
          <button
            onClick={() => window.location.reload()}
            className="mt-4 px-4 py-2 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors"
          >
            Перезагрузить страницу
          </button>
        </div>
      </div>
    );
  }

  return children;
};

// Компонент для обертки ленивой загрузки
const LazyLoad = ({ children }) => (
  <ErrorBoundary>
    <Suspense fallback={<LoadingSpinner />}>
      {children}
    </Suspense>
  </ErrorBoundary>
);

const AppRoutes = () => {
  return (
    <Routes>
      <Route path="/" element={<LazyLoad><HomePage /></LazyLoad>} />
      <Route path="/catalog" element={<LazyLoad><CatalogPage /></LazyLoad>} />
      <Route path="/media/:path" element={<LazyLoad><MediaOverviewPage /></LazyLoad>} />
      <Route path="/rating" element={<LazyLoad><RatingPage /></LazyLoad>} />
      <Route path="/forgot-password" element={<LazyLoad><ForgotPasswordPage /></LazyLoad>} />

      <Route path="/profile" element={<AuthRoute><LazyLoad><ProfilePage /></LazyLoad></AuthRoute>} />
      <Route path="/profile/:login" element={<LazyLoad><ProfilePage /></LazyLoad>} />
      <Route path="/profile/telegram-link" element={<AuthRoute><TelegramAuth /></AuthRoute>} />

      <Route path="/auth" element={<GuestRoute />}>
        <Route path="login" element={<LazyLoad><LoginPage /></LazyLoad>} />
        <Route path="register" element={<LazyLoad><RegisterPage /></LazyLoad>} />
      </Route>

      {/* Временно отключена авторизация через Telegram
      <Route path="/auth/telegram" element={<TelegramAuth />} />
      */}

      <Route path="/admin" element={<AdminRoute />}>
        <Route element={<AdminLayout />}>
          <Route index element={<LazyLoad><AdminDashboard /></LazyLoad>} />
          <Route path="media" element={<LazyLoad><AdminMediaPage /></LazyLoad>} />
          <Route path="media/:mediaId/seasons" element={<LazyLoad><AdminSeasonsPage /></LazyLoad>} />
          <Route path="users" element={<LazyLoad><AdminUsersPage /></LazyLoad>} />
          <Route path="seasons" element={<LazyLoad><AdminSeasonsPage /></LazyLoad>} />
          <Route path="achievements" element={<LazyLoad><AdminAchievementsPage /></LazyLoad>} />
          <Route path="support" element={<LazyLoad><AdminSupportPage /></LazyLoad>} />
          <Route path="suggestions" element={<LazyLoad><AdminSuggestionsPage /></LazyLoad>} />
        </Route>
      </Route>

      <Route path="/support" element={<AuthRoute />}>
        <Route index element={<LazyLoad><SupportPage /></LazyLoad>} />
      </Route>

      <Route path="/privacy-policy" element={<LazyLoad><PrivacyPolicyPage /></LazyLoad>} />
      <Route path="/terms-of-service" element={<LazyLoad><TermsOfServicePage /></LazyLoad>} />
      <Route path="/user-agreement" element={<LazyLoad><UserAgreementPage /></LazyLoad>} />

      <Route path="*" element={<LazyLoad><NotFoundPage /></LazyLoad>} />
    </Routes>
  );
};

export default AppRoutes; 