import React, { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { Archive, GraduationCap, LayoutTemplate, School, Users } from 'lucide-react'

import { Button } from '@/components/ui/button'
import { Toaster } from '@/components/ui/sonner'
import ClassesPage from '@/pages/classes-page'
import TemplatesPage from '@/pages/templates-page'
import GeneratedPage from '@/pages/generated-page'
import StudentsPage from '@/pages/students-page'
import '@/globals.css'

const NAV_ITEMS = [
  { href: '/classes', label: '班级管理', Icon: School },
  { href: '/students', label: '幼儿管理', Icon: Users },
  { href: '/templates', label: '证书模板', Icon: LayoutTemplate },
  { href: '/generated', label: '生成完成', Icon: Archive }
]

function useCurrentPath() {
  const [path, setPath] = useState(window.location.pathname)

  useEffect(() => {
    const handleNavigation = () => setPath(window.location.pathname)
    window.addEventListener('popstate', handleNavigation)

    return () => window.removeEventListener('popstate', handleNavigation)
  }, [])

  return path
}

function navigate(href: string) {
  window.history.pushState(null, '', href)
  window.dispatchEvent(new PopStateEvent('popstate'))
}

function CurrentPage({ path }: { path: string }) {
  if (path.startsWith('/templates')) {
    return <TemplatesPage />
  }

  if (path.startsWith('/generated')) {
    return <GeneratedPage />
  }

  if (path.startsWith('/students')) {
    return <StudentsPage />
  }

  return <ClassesPage />
}

function App() {
  const path = useCurrentPath()

  return (
    <>
      <main className="min-h-screen bg-background">
        <div className="grid min-h-screen lg:grid-cols-[260px_1fr]">
          <aside className="border-r bg-card p-4">
            <div className="mb-6 flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-md bg-primary text-primary-foreground">
                <GraduationCap className="h-5 w-5" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">后台管理</p>
                <h1 className="font-semibold">毕业证书</h1>
              </div>
            </div>
            <nav className="space-y-2">
              {NAV_ITEMS.map(({ href, label, Icon }) => (
                <Button
                  key={href}
                  type="button"
                  variant={path.startsWith(href) ? 'secondary' : 'ghost'}
                  className="w-full justify-start"
                  onClick={() => navigate(href)}
                >
                  <Icon />
                  {label}
                </Button>
              ))}
            </nav>
          </aside>

          <section className="min-w-0 p-5">
            <CurrentPage path={path} />
          </section>
        </div>
      </main>
      <Toaster />
    </>
  )
}

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)
