import { useState, useEffect } from 'react';
import { Box, Container, Paper } from '@mui/material';
import { Routes, Route, HashRouter } from 'react-router-dom';

// Import pages
import HomePage from './pages/HomePage';
import SessionPage from './pages/SessionPage';
import KeypairPage from './pages/KeypairPage';
import ScriptPage from './pages/ScriptPage';
import SettingsPage from './pages/SettingsPage';
import WebSocketPage from './pages/WebSocketPage';
import CryptoPage from './pages/CryptoPage';

// Import components
import Header from './components/Header';
import Navigation from './components/Navigation';

// Import session state management
import { useSessionStore } from './store/sessionStore';

function App() {
  const { checkSessionStatus, initWasm } = useSessionStore();
  const [isLoading, setIsLoading] = useState(true);
  const [wasmError, setWasmError] = useState<string | null>(null);

  // Initialize WASM and check session status on mount
  useEffect(() => {
    const initializeApp = async () => {
      try {
        // First initialize WASM module
        const wasmInitialized = await initWasm();
        
        if (!wasmInitialized) {
          throw new Error('Failed to initialize WASM module');
        }
        
        // Then check session status
        await checkSessionStatus();
      } catch (error) {
        console.error('Initialization error:', error);
        setWasmError((error as Error).message || 'Failed to initialize the extension');
      } finally {
        setIsLoading(false);
      }
    };
    
    initializeApp();
  }, [checkSessionStatus, initWasm]);

  if (isLoading) {
    return (
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
        }}
      >
        Loading...
      </Box>
    );
  }
  
  if (wasmError) {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          p: 3,
          textAlign: 'center',
        }}
      >
        <Paper sx={{ p: 3, maxWidth: 400 }}>
          <h6 style={{ color: 'red', marginBottom: '8px' }}>
            WASM Module Failed to Initialize
          </h6>
          <p style={{ marginBottom: '16px' }}>
            The WASM module could not be loaded. Please try reloading the extension.
          </p>
          <p style={{ fontSize: '0.875rem', color: 'gray' }}>
            Error: {wasmError} Please contact support if the problem persists.
          </p>
        </Paper>
      </Box>
    );
  }

  return (
    <HashRouter>
      <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
        <Header />
        
        <Container component="main" sx={{ flexGrow: 1, overflow: 'auto', py: 2 }}>
          <Paper 
            elevation={3} 
            sx={{ 
              p: 2, 
              height: '100%', 
              display: 'flex', 
              flexDirection: 'column',
              overflow: 'hidden'
            }}
          >
            <Routes>
              <Route path="/" element={<HomePage />} />
              <Route path="/session" element={<SessionPage />} />
              <Route path="/keypair" element={<KeypairPage />} />
              <Route path="/crypto" element={<CryptoPage />} />
              <Route path="/script" element={<ScriptPage />} />
              <Route path="/websocket" element={<WebSocketPage />} />
              <Route path="/settings" element={<SettingsPage />} />
            </Routes>
          </Paper>
        </Container>
        
        <Navigation />
      </Box>
    </HashRouter>
  );
}

export default App;
