import * as Dialog from '@radix-ui/react-dialog'
import { BookOpenText, Menu, MessageSquareText, X } from 'lucide-react'
import { useState } from 'react'
import { NavLink, Outlet } from 'react-router-dom'

import { Button } from '../components/ui/button'
import { SessionList } from '../features/chat/SessionList'
import { cn } from '../lib/utils'

function Navigation({ onNavigate }: { onNavigate?: () => void }) {
  return (
    <>
      <div className="brand-lockup">
        <span className="brand-lockup__mark">K</span>
        <span><strong>KNOWLEDGE</strong><small>DESK · 本地知识台</small></span>
      </div>
      <p className="nav-label">工作区</p>
      <nav className="primary-nav" aria-label="主导航">
        <NavLink to="/chat" onClick={onNavigate} className={({ isActive }) => cn('nav-item', isActive && 'nav-item--active')}>
          <MessageSquareText size={17} /><span>知识对话</span>
        </NavLink>
        <NavLink to="/documents" onClick={onNavigate} className={({ isActive }) => cn('nav-item', isActive && 'nav-item--active')}>
          <BookOpenText size={17} /><span>文档资料库</span>
        </NavLink>
      </nav>
      <SessionList onNavigate={onNavigate} />
      <div className="sidebar-note">
        <span className="status-dot" />
        <div><strong>严格知识库模式</strong><small>回答必须引用已索引资料</small></div>
      </div>
      <p className="sidebar-version">KBQA · LOCAL / 0.1</p>
    </>
  )
}

export function AppLayout() {
  const [menuOpen, setMenuOpen] = useState(false)
  return (
    <div className="app-shell">
      <aside className="sidebar"><Navigation /></aside>
      <header className="mobile-header">
        <span className="brand-lockup__mark">K</span><strong>KNOWLEDGE DESK</strong>
        <Dialog.Root open={menuOpen} onOpenChange={setMenuOpen}>
          <Dialog.Trigger asChild><Button variant="ghost" size="icon" aria-label="打开导航"><Menu /></Button></Dialog.Trigger>
          <Dialog.Portal>
            <Dialog.Overlay className="dialog-overlay" />
            <Dialog.Content className="mobile-menu">
              <Dialog.Title className="sr-only">导航</Dialog.Title>
              <Dialog.Close asChild><Button className="mobile-menu__close" variant="ghost" size="icon" aria-label="关闭导航"><X /></Button></Dialog.Close>
              <Navigation onNavigate={() => setMenuOpen(false)} />
            </Dialog.Content>
          </Dialog.Portal>
        </Dialog.Root>
      </header>
      <main className="route-canvas"><Outlet /></main>
    </div>
  )
}
