import { useEffect, useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { AuthProvider, useAuth } from './context/AuthContext';
import { Layout } from './components/layout/Layout';
import { DeepLinkHandler } from './components/DeepLinkHandler';
import { LoginPage } from './pages/LoginPage';
import { HomePage } from './pages/HomePage';
import { QuizPage } from './pages/QuizPage';
import { ShopPage } from './pages/ShopPage';
import { ProfilePage } from './pages/ProfilePage';
import { QRScannerPage } from './pages/QRScannerPage';
import { QuizResultPage } from './pages/QuizResultPage';
import { AdminPage } from './pages/AdminPage';
import theme from './theme';

// Component to handle Telegram auto-authentication
const TelegramAuthHandler: React.FC = () => {
  const { login, isAuthenticated, loading } = useAuth();
  const [authAttempted, setAuthAttempted] = useState(false);

  useEffect(() => {
    const handleTelegramAuth = async () => {
      if (window.Telegram?.WebApp && !isAuthenticated && !authAttempted && !loading) {
        const initData = window.Telegram.WebApp.initData;
        if (initData) {
          console.log('Attempting auto-auth with Telegram initData');
          setAuthAttempted(true);
          const success = await login(initData);
          if (success) {
            console.log('Auto-auth successful');
          } else {
            console.log('Auto-auth failed');
          }
        }
      }
    };

    handleTelegramAuth();
  }, [isAuthenticated, authAttempted, loading, login]);

  return null;
};

function App() {
  useEffect(() => {
    if (window.Telegram?.WebApp) {
      const webApp = window.Telegram.WebApp;

      // Initialize Telegram Web App
      webApp.ready();
      webApp.expand();

      // Optional features
      webApp.enableClosingConfirmation?.();

      // Set theme colors if available
      webApp.setBackgroundColor?.('#0F0F0F');
      webApp.setHeaderColor?.('#1A1A1A');

      // Handle viewport changes if available
      const handleViewportChanged = () => {
        webApp.expand();
      };

      webApp.onEvent?.('viewportChanged', handleViewportChanged);

      return () => {
        webApp.offEvent?.('viewportChanged', handleViewportChanged);
      };
    }
  }, []);

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <AuthProvider>
        <Router>
          <Layout>
            <Routes>
              <Route path="/" element={<Navigate to="/home" replace />} />
              <Route path="/home" element={<><TelegramAuthHandler /><HomePage /></>} />
              <Route path="/quiz/:id" element={<QuizPage />} />
              <Route path="/quiz-result" element={<QuizResultPage />} />
              <Route path="/shop" element={<ShopPage />} />
              <Route path="/profile" element={<ProfilePage />} />
              <Route path="/qr-scanner" element={<QRScannerPage />} />
              <Route path="/admin" element={<AdminPage />} />
              <Route path="/login" element={<LoginPage />} />
              <Route path="*" element={<Navigate to="/home" replace />} />
            </Routes>
            <DeepLinkHandler />
          </Layout>
        </Router>
      </AuthProvider>
    </ThemeProvider>
  );
}

export default App
