import React, { useEffect } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { useWebSocket } from './hooks/useWebSocket'
import { useSystemStore } from './stores/systemStore'

// Layout components
import Layout from './components/layout/Layout'

// Page components
import Dashboard from './pages/Dashboard'
import ProcessControl from './pages/ProcessControl'
import RecipeManagement from './pages/RecipeManagement'
import HardwareStatus from './pages/HardwareStatus'
import SystemSettings from './pages/SystemSettings'
import UserManagement from './pages/UserManagement'

// Error boundary
import ErrorBoundary from './components/common/ErrorBoundary'

function App() {
  const { connect, disconnect, isConnected } = useWebSocket()
  const { initializeSystem, isInitialized } = useSystemStore()

  useEffect(() => {
    // Initialize the system on app start
    initializeSystem()
    
    // Connect to WebSocket for real-time updates
    connect()
    
    return () => {
      disconnect()
    }
  }, [initializeSystem, connect, disconnect])

  if (!isInitialized) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-primary-600 mx-auto mb-4"></div>
          <h2 className="text-xl font-semibold text-gray-900">
            Initializing Tempering System...
          </h2>
          <p className="text-gray-600 mt-2">
            Please wait while we connect to the hardware
          </p>
        </div>
      </div>
    )
  }

  return (
    <ErrorBoundary>
      <div className="App min-h-screen bg-gray-50">
        <Layout isConnected={isConnected}>
          <Routes>
            {/* Default route redirects to dashboard */}
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            
            {/* Main application routes */}
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/process" element={<ProcessControl />} />
            <Route path="/recipes" element={<RecipeManagement />} />
            <Route path="/hardware" element={<HardwareStatus />} />
            <Route path="/settings" element={<SystemSettings />} />
            <Route path="/users" element={<UserManagement />} />
            
            {/* Catch-all route for 404s */}
            <Route path="*" element={<Navigate to="/dashboard" replace />} />
          </Routes>
        </Layout>
      </div>
    </ErrorBoundary>
  )
}

export default App
