import { ChevronLeft, ChevronRight, FileSearch, X } from 'lucide-react'
import { useEffect, useState } from 'react'

import { Button } from '../../components/ui/button'
import type { Chunk, Document } from '../../lib/types'
import { getDocument, listChunks } from './api'

type Props = { documentId?: string; onClose?: () => void }

export function DocumentDetail({ documentId, onClose }: Props) {
  const [document, setDocument] = useState<Document | null>(null)
  const [chunks, setChunks] = useState<Chunk[]>([])
  const [offset, setOffset] = useState(0)
  const [total, setTotal] = useState(0)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!documentId) return
    let active = true
    void Promise.all([getDocument(documentId), listChunks(documentId, offset, 10)])
      .then(([nextDocument, page]) => {
        if (!active) return
        setDocument(nextDocument); setChunks(page.items); setTotal(page.total); setError(null)
      })
      .catch((reason) => { if (active) setError(reason instanceof Error ? reason.message : '详情加载失败') })
    return () => { active = false }
  }, [documentId, offset])

  if (!documentId) return <aside className="detail-panel detail-panel--empty"><FileSearch size={24} /><strong>选择一份文档</strong><span>分块原文和索引信息会显示在这里。</span></aside>
  return (
    <aside className="detail-panel">
      <header className="detail-panel__header">
        <div><p className="eyebrow">DOCUMENT DETAIL</p><h2>{document?.filename ?? '加载中…'}</h2></div>
        {onClose && <Button variant="ghost" size="icon" onClick={onClose} aria-label="关闭详情"><X size={17} /></Button>}
      </header>
      {error && <p className="panel-error">{error}</p>}
      {document && <dl className="document-meta"><div><dt>状态</dt><dd>{document.status}</dd></div><div><dt>分块</dt><dd>{document.chunk_count}</dd></div><div><dt>类型</dt><dd>{document.file_type.toUpperCase()}</dd></div></dl>}
      <div className="chunk-list">
        {chunks.map((chunk) => <article key={chunk.id} className="chunk-card"><div><span>#{chunk.order_index + 1}</span>{chunk.page_number && <span>第 {chunk.page_number} 页</span>}</div><p>{chunk.content}</p></article>)}
        {document?.status !== 'indexed' && chunks.length === 0 && <p className="muted-copy">文档索引完成后可查看分块原文。</p>}
      </div>
      {total > 10 && <footer className="detail-pagination"><Button variant="ghost" size="icon" disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - 10))}><ChevronLeft /></Button><span>{offset + 1}–{Math.min(offset + 10, total)} / {total}</span><Button variant="ghost" size="icon" disabled={offset + 10 >= total} onClick={() => setOffset(offset + 10)}><ChevronRight /></Button></footer>}
    </aside>
  )
}
