import React, { useState, useEffect } from 'react'
import { Layout } from './components/Layout'
import { DashboardOverview } from './components/DashboardOverview'
import { Dashboard } from './components/Dashboard'
import { DocumentDetail } from './components/DocumentDetail'
import { Training } from './components/Training'
import { DatasetDetail } from './components/DatasetDetail'
import { Models } from './components/Models'
import { Login } from './components/Login'
import { InferenceDemo } from './components/InferenceDemo'

const App: React.FC = () => {
  const [currentView, setCurrentView] = useState('dashboard')
  const [selectedDocId, setSelectedDocId] = useState<string | null>(null)
  const [isAuthenticated, setIsAuthenticated] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem('admin_token')
    setIsAuthenticated(!!token)
  }, [])

  const handleNavigate = (view: string, docId?: string) => {
    setCurrentView(view)
    if (docId) {
      setSelectedDocId(docId)
    }
  }

  const handleLogin = (token: string) => {
    setIsAuthenticated(true)
  }

  const handleLogout = () => {
    localStorage.removeItem('admin_token')
    setIsAuthenticated(false)
    setCurrentView('documents')
  }

  if (!isAuthenticated) {
    return <Login onLogin={handleLogin} />
  }

  const renderContent = () => {
    switch (currentView) {
      case 'dashboard':
        return <DashboardOverview onNavigate={handleNavigate} />
      case 'documents':
        return <Dashboard onNavigate={handleNavigate} />
      case 'detail':
        return (
          <DocumentDetail
            docId={selectedDocId || '1'}
            onBack={() => setCurrentView('documents')}
          />
        )
      case 'demo':
        return <InferenceDemo />
      case 'training':
        return <Training onNavigate={handleNavigate} />
      case 'dataset-detail':
        return (
          <DatasetDetail
            datasetId={selectedDocId || ''}
            onBack={() => setCurrentView('training')}
          />
        )
      case 'models':
        return <Models />
      default:
        return <DashboardOverview onNavigate={handleNavigate} />
    }
  }

  return (
    <Layout activeView={currentView} onNavigate={handleNavigate} onLogout={handleLogout}>
      {renderContent()}
    </Layout>
  )
}

export default App
