import {
  BookOpen,
  LayoutDashboard,
  LogOut,
  ShieldCheck,
  Users
} from 'lucide-react'
import { NavLink, Navigate, Outlet, useNavigate } from 'react-router-dom'
import { Brand } from '../../components/Brand'
import { Footer } from '../../components/Footer'
import { useAuth } from '../../AuthContext'

export function AdminLayout() {
  const { user, loading, logout } = useAuth()
  const navigate = useNavigate()

  if (loading) return <div className="center-loading">正在加载管理后台…</div>

  // 未登录或非管理员，统一拦截跳转至管理员专属登录页 /admin/login
  if (!user || user.role !== 'ADMIN') {
    return <Navigate to="/admin/login" replace />
  }

  const handleAdminLogout = async () => {
    await logout()
    navigate('/admin/login', { replace: true })
  }

  return (
    <div className="admin-shell">
      <header className="admin-topbar">
        <div className="admin-brand-wrap">
          <NavLink to="/admin" className="logo-link">
            <Brand />
          </NavLink>
          <div className="admin-badge">
            <ShieldCheck size={14} />
            <span>管理后台</span>
          </div>
        </div>

        <nav className="admin-nav">
          <NavLink to="/admin" end className={({ isActive }) => (isActive ? 'active' : '')}>
            <LayoutDashboard size={16} />
            <span>概览看板</span>
          </NavLink>
          <NavLink to="/admin/courses" className={({ isActive }) => (isActive ? 'active' : '')}>
            <BookOpen size={16} />
            <span>课程制作</span>
          </NavLink>
          <NavLink to="/admin/users" className={({ isActive }) => (isActive ? 'active' : '')}>
            <Users size={16} />
            <span>用户管理</span>
          </NavLink>
        </nav>

        <div className="admin-top-actions">
          <div className="admin-user-info">
            <strong>{user.contactName || '系统管理员'}</strong>
            <small>{user.phone}</small>
          </div>
          <button className="icon-button" title="退出管理员登录" onClick={handleAdminLogout}>
            <LogOut size={18} />
          </button>
        </div>
      </header>

      <main className="admin-main">
        <Outlet />
      </main>
      <Footer />
    </div>
  )
}
