import {
  MemoryRouter as Router,
  Routes,
  Route,
  Navigate,
  useNavigate,
} from 'react-router-dom';
import Login from './pages/Login';
import LaunchPage from './pages/LaunchPage';
import { ReactNode, useEffect, useState } from 'react';
import './App.css';
import TopBar from './components/TopBar';
import { Box } from '@mui/material';
import MinecraftBackround from './components/MinecraftBackround';
import { Notifier } from './components/Notifier';
import { VersionsExplorer } from './pages/VersionsExplorer';

const AuthCheck = ({ children }: { children: ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const savedConfig = localStorage.getItem('launcher_config');
        if (savedConfig) {
          const config = JSON.parse(savedConfig);
          if (config.accessToken) {
            // Можно добавить дополнительную проверку токена
            const isValid = await validateToken(config.accessToken);
            setIsAuthenticated(isValid);
            return;
          }
        }
        setIsAuthenticated(false);
      } catch (error) {
        console.error('Ошибка проверки авторизации:', error);
        setIsAuthenticated(false);
      }
    };

    checkAuth();
  }, []);

  const validateToken = async (token: string) => {
    try {
      const response = await fetch('https://authserver.ely.by/auth/validate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ accessToken: token }),
      });
      return response.ok;
    } catch (error) {
      return false;
    }
  };

  if (isAuthenticated === null) {
    return <div>Loading...</div>;
  }

  return isAuthenticated ? children : <Navigate to="/login" replace />;
};

const App = () => {
  // Просто используйте window.open без useNavigate
  const handleRegister = () => {
    window.open('https://account.ely.by/register', '_blank');
  };

  return (
    <Router>
      <Box
        sx={{
          height: '100vh',
          width: '100vw',
          position: 'relative',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <MinecraftBackround />
        <TopBar onRegister={handleRegister} />
        <Notifier />
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route
            path="/"
            element={
              <AuthCheck>
                <VersionsExplorer />
              </AuthCheck>
            }
          />
          <Route
            path="/launch/:versionId"
            element={
              <AuthCheck>
                <LaunchPage />
              </AuthCheck>
            }
          />
        </Routes>
      </Box>
    </Router>
  );
};

export default App;
