import {
  MemoryRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import Login from './pages/Login';
import LaunchPage from './pages/LaunchPage';
import { ReactNode, useEffect, useState } from 'react';
import './App.css';

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 = () => {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route
          path="/"
          element={
            <AuthCheck>
              <LaunchPage />
            </AuthCheck>
          }
        />
      </Routes>
    </Router>
  );
};

export default App;
