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 MinecraftBackground from './components/MinecraftBackground';
import { Notifier } from './components/Notifier';
import { VersionsExplorer } from './pages/VersionsExplorer';
import Profile from './pages/Profile';
import Shop from './pages/Shop';
import Marketplace from './pages/Marketplace';
import { Registration } from './pages/Registration';
import { FullScreenLoader } from './components/FullScreenLoader';
import { News } from './pages/News';
import PageHeader from './components/PageHeader';
import { useLocation } from 'react-router-dom';
import DailyReward from './pages/DailyReward';
import DailyQuests from './pages/DailyQuests';
import Settings from './pages/Settings';

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,
              config.clientToken,
            );
            setIsAuthenticated(isValid);
            return;
          }
        }
        setIsAuthenticated(false);
      } catch (error) {
        console.error('Ошибка проверки авторизации:', error);
        setIsAuthenticated(false);
      }
    };

    checkAuth();
  }, []);

  const validateToken = async (accessToken: string, clientToken: string) => {
    try {
      // Используем IPC для валидации токена через main процесс
      const result = await window.electron.ipcRenderer.invoke(
        'validate-token',
        { accessToken, clientToken },
      );

      // Если токен недействителен, очищаем сохраненные данные в localStorage
      if (!result.valid) {
        console.log(
          'Токен недействителен, очищаем данные авторизации из localStorage',
        );
        const savedConfig = localStorage.getItem('launcher_config');
        if (savedConfig) {
          const config = JSON.parse(savedConfig);
          // Сохраняем только логин и другие настройки, но удаляем токены
          const cleanedConfig = {
            username: config.username,
            memory: config.memory || 4096,
            comfortVersion: config.comfortVersion || '',
            password: '', // Очищаем пароль для безопасности
          };
          localStorage.setItem(
            'launcher_config',
            JSON.stringify(cleanedConfig),
          );
        }
      }

      return result.valid;
    } catch (error) {
      console.error('Ошибка проверки токена:', error);
      return false;
    }
  };

  if (isAuthenticated === null) {
    return <FullScreenLoader message="Загрузка..." />;
  }

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

const App = () => {
  return (
    <Router>
      <AppLayout />
    </Router>
  );
};

const AppLayout = () => {
  // Просто используйте window.open без useNavigate
  const handleRegister = () => {
    window.open('https://account.ely.by/register', '_blank');
  };
  const [username, setUsername] = useState<string | null>(null);
  const location = useLocation();
  const path = location.pathname;

  useEffect(() => {
    const savedConfig = localStorage.getItem('launcher_config');
    if (savedConfig) {
      const config = JSON.parse(savedConfig);
      if (config.username) {
        setUsername(config.username);
      }
    }
  }, []);

  return (
    <Box
      sx={{
        height: '100vh',
        width: '100vw',
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: location.pathname === '/profile' || location.pathname.startsWith('/launch') || location.pathname === '/login' || location.pathname === '/registration'
          ? 'center'
          : 'flex-start',
        overflowX: 'hidden',
      }}
    >
        <MinecraftBackground />
        <TopBar onRegister={handleRegister} username={username || ''} />
        <PageHeader />
        <Notifier />

      <Routes>
          <Route
            path="/login"
            element={<Login onLoginSuccess={setUsername} />}
          />
          <Route path="/registration" element={<Registration />} />
          <Route
            path="/"
            element={
              <AuthCheck>
                <VersionsExplorer />
              </AuthCheck>
            }
          />
          <Route
            path="/launch/:versionId"
            element={
              <AuthCheck>
                <LaunchPage />
              </AuthCheck>
            }
          />
          <Route
            path="/profile"
            element={
              <AuthCheck>
                <Profile />
              </AuthCheck>
            }
          />
          <Route
            path="/daily"
            element={
              <AuthCheck>
                <DailyReward />
              </AuthCheck>
            }
          />
          <Route
            path="/dailyquests"
            element={
              <AuthCheck>
                <DailyQuests />
              </AuthCheck>
            }
          />
          <Route
            path="/settings"
            element={
              <AuthCheck>
                <Settings />
              </AuthCheck>
            }
          />
          <Route
            path="/shop"
            element={
              <AuthCheck>
                <Shop />
              </AuthCheck>
            }
          />
          <Route
            path="/marketplace"
            element={
              <AuthCheck>
                <Marketplace />
              </AuthCheck>
            }
          />
          <Route
            path="/news"
            element={
              <AuthCheck>
                <News />
              </AuthCheck>
            }
          />
      </Routes>
    </Box>
  );
};

export default App;
