import * as Dialog from '@radix-ui/react-dialog'
import { Archive, FileCheck2, Filter, LoaderCircle, PanelRightOpen, TriangleAlert } from 'lucide-react'
import { useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'

import { Button } from '../../components/ui/button'
import type { DocumentStatus } from '../../lib/types'
import { cn } from '../../lib/utils'
import { deleteDocument, retryDocument } from './api'
import { DocumentDetail } from './DocumentDetail'
import { DocumentList } from './DocumentList'
import { UploadDocument } from './UploadDocument'
import { useDocuments } from './useDocuments'

const FILTERS: Array<{ value?: DocumentStatus; label: string }> = [
  { label: '全部资料' },
  { value: 'indexed', label: '已索引' },
  { value: 'indexing', label: '处理中' },
  { value: 'failed', label: '失败' },
]

export function DocumentsPage() {
  const { documentId } = useParams()
  const navigate = useNavigate()
  const [filter, setFilter] = useState<DocumentStatus | undefined>()
  const [detailOpen, setDetailOpen] = useState(false)
  const { documents, loading, error, refresh } = useDocuments(filter)
  const counts = useMemo(() => ({
    indexed: documents.filter((item) => item.status === 'indexed').length,
    active: documents.filter((item) => ['pending', 'indexing'].includes(item.status)).length,
    failed: documents.filter((item) => item.status === 'failed').length,
  }), [documents])

  function selectDocument(id: string) { navigate(`/documents/${id}`); setDetailOpen(true) }

  async function retry(id: string) { await retryDocument(id); await refresh() }
  async function remove(id: string) {
    const document = documents.find((item) => item.id === id)
    if (!window.confirm(`确定删除“${document?.filename ?? '此文档'}”及全部索引吗？`)) return
    await deleteDocument(id)
    if (documentId === id) navigate('/documents')
    await refresh()
  }

  return (
    <section className="documents-workspace">
      <main className="documents-main">
        <header className="page-header">
          <div><p className="eyebrow">DOCUMENT LIBRARY</p><h1>文档资料库</h1><p>管理提供给研究 Agent 的唯一事实来源。</p></div>
          <UploadDocument onUploaded={(id) => { selectDocument(id); void refresh() }} />
        </header>
        <div className="metric-strip">
          <div><Archive size={17} /><span><strong>{documents.length}</strong> 当前列表</span></div>
          <div><FileCheck2 size={17} /><span><strong>{counts.indexed}</strong> 已索引</span></div>
          <div><LoaderCircle size={17} /><span><strong>{counts.active}</strong> 处理中</span></div>
          <div><TriangleAlert size={17} /><span><strong>{counts.failed}</strong> 需处理</span></div>
        </div>
        <div className="document-toolbar">
          <div className="filter-tabs"><Filter size={14} />{FILTERS.map((item) => <button key={item.label} className={cn(filter === item.value && 'is-active')} onClick={() => setFilter(item.value)}>{item.label}</button>)}</div>
          {documentId && <Button className="detail-trigger" variant="secondary" size="sm" onClick={() => setDetailOpen(true)}><PanelRightOpen size={15} />查看详情</Button>}
        </div>
        {error && <p className="panel-error">{error}</p>}
        {loading ? <div className="loading-state"><LoaderCircle className="spin" />正在读取资料库…</div> : <DocumentList documents={documents} selectedId={documentId} onSelect={selectDocument} onRetry={(id) => void retry(id)} onDelete={(id) => void remove(id)} />}
      </main>
      <div className="documents-detail-desktop"><DocumentDetail key={documentId ?? 'empty'} documentId={documentId} /></div>
      <Dialog.Root open={detailOpen} onOpenChange={setDetailOpen}>
        <Dialog.Portal><Dialog.Overlay className="dialog-overlay" /><Dialog.Content className="evidence-drawer"><Dialog.Title className="sr-only">文档详情</Dialog.Title><DocumentDetail key={`drawer-${documentId ?? 'empty'}`} documentId={documentId} onClose={() => setDetailOpen(false)} /></Dialog.Content></Dialog.Portal>
      </Dialog.Root>
    </section>
  )
}
