import { useState, useEffect } from 'react'
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import { auth } from '../utils/api'
import AdminLogin from './pages/Login'
import AdminDashboard from './pages/Dashboard'
import AdminPosts from './pages/Posts'
import AdminPostEditor from './pages/PostEditor'
import AdminCategories from './pages/Categories'
import AdminMedia from './pages/MediaLibrary'
import AdminSettings from './pages/Settings'
import AdminSidebar from './components/Sidebar'

export default function AdminApp() {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          await auth.verify()
          setIsAuthenticated(true)
        } catch {
          localStorage.removeItem('token')
          setIsAuthenticated(false)
        }
      }
      setLoading(false)
    }
    checkAuth()
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return <AdminLogin onSuccess={() => setIsAuthenticated(true)} />
  }

  return (
    <div className="flex min-h-screen bg-gray-100">
      <AdminSidebar onLogout={() => setIsAuthenticated(false)} />
      <main className="flex-1 overflow-auto">
        <Routes>
          <Route path="/" element={<AdminDashboard />} />
          <Route path="/posts" element={<AdminPosts />} />
          <Route path="/posts/new" element={<AdminPostEditor />} />
          <Route path="/posts/:id/edit" element={<AdminPostEditor />} />
          <Route path="/categories" element={<AdminCategories />} />
          <Route path="/media" element={<AdminMedia />} />
          <Route path="/settings" element={<AdminSettings />} />
          <Route path="*" element={<Navigate to="/admin" replace />} />
        </Routes>
      </main>
    </div>
  )
}
