import { useState } from 'react'
import { Loader2 } from 'lucide-react'
import { AnimatePresence } from 'framer-motion'
import { AppProvider, useApp } from './lib/AppContext'
import { PageFade } from './components/motion'
import Setup from './pages/Setup'
import Login from './pages/Login'
import Layout, { Page } from './components/Layout'
import Dashboard from './pages/Dashboard'
import Kanban from './pages/Kanban'
import Milestones from './pages/Milestones'
import Bugs from './pages/Bugs'
import Members from './pages/Members'

const PAGES: Record<Page, () => JSX.Element> = {
  dashboard: Dashboard,
  kanban: Kanban,
  milestones: Milestones,
  bugs: Bugs,
  members: Members
}

function Shell(): JSX.Element {
  const { stage } = useApp()
  const [page, setPage] = useState<Page>('dashboard')

  if (stage === 'loading') {
    return (
      <div className="flex h-full items-center justify-center text-gray-400">
        <Loader2 className="animate-spin" size={28} />
      </div>
    )
  }
  if (stage === 'setup') return <Setup />
  if (stage === 'login') return <Login />

  const ActivePage = PAGES[page]
  return (
    <Layout page={page} setPage={setPage}>
      <AnimatePresence mode="wait">
        <PageFade key={page}>
          <ActivePage />
        </PageFade>
      </AnimatePresence>
    </Layout>
  )
}

export default function App(): JSX.Element {
  return (
    <AppProvider>
      <Shell />
    </AppProvider>
  )
}
