import { useEffect } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { useAuthStore } from './stores/authStore'
import { wsClient } from './api/client'
import Layout from './components/Layout'
import LoginPage from './pages/LoginPage'
import WorkflowsPage from './pages/WorkflowsPage'
import WorkflowEditorPage from './pages/WorkflowEditorPage'
import ExecutionsPage from './pages/ExecutionsPage'
import SettingsPage from './pages/SettingsPage'
import NodesPage from './pages/NodesPage'
import DatabasePage from './pages/DatabasePage'
import CredentialsPage from './pages/CredentialsPage'

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />
}

function App() {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  // Connect WebSocket when app loads if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      wsClient.connect()
    }
    return () => {
      wsClient.disconnect()
    }
  }, [isAuthenticated])

  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/"
        element={
          <PrivateRoute>
            <Layout />
          </PrivateRoute>
        }
      >
        <Route index element={<Navigate to="/workflows" replace />} />
        <Route path="workflows" element={<WorkflowsPage />} />
        <Route path="workflows/:id" element={<WorkflowEditorPage />} />
        <Route path="executions" element={<ExecutionsPage />} />
        <Route path="nodes" element={<NodesPage />} />
        <Route path="credentials" element={<CredentialsPage />} />
        <Route path="database" element={<DatabasePage />} />
        <Route path="settings" element={<SettingsPage />} />
      </Route>
    </Routes>
  )
}

export default App
