import { FileText, MoreHorizontal, RefreshCw, Trash2 } from 'lucide-react'

import { Badge } from '../../components/ui/badge'
import { Button } from '../../components/ui/button'
import type { Document } from '../../lib/types'
import { cn } from '../../lib/utils'

const STATUS_LABEL = {
  pending: '等待索引', indexing: '索引中', indexed: '已索引', failed: '失败', deleting: '删除中',
} as const

function formatSize(bytes: number) {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / 1024 ** 2).toFixed(1)} MB`
}

type Props = {
  documents: Document[]
  selectedId?: string
  onSelect: (id: string) => void
  onRetry: (id: string) => void
  onDelete: (id: string) => void
}

export function DocumentList({ documents, selectedId, onSelect, onRetry, onDelete }: Props) {
  if (documents.length === 0) {
    return <div className="list-empty"><FileText size={24} /><strong>资料库还是空的</strong><span>上传第一份文档，系统会在后台建立索引。</span></div>
  }
  return (
    <div className="document-list">
      {documents.map((document) => (
        <article key={document.id} className={cn('document-row', selectedId === document.id && 'document-row--selected')} onClick={() => onSelect(document.id)}>
          <div className="file-glyph">{document.file_type.toUpperCase()}</div>
          <div className="document-row__body">
            <strong title={document.filename}>{document.filename}</strong>
            <span>{formatSize(document.file_size)} · {document.chunk_count ? `${document.chunk_count} 个分块` : '尚无分块'}</span>
            {document.error_message && <small>{document.error_message}</small>}
          </div>
          <Badge className={`status status--${document.status}`}><span />{STATUS_LABEL[document.status]}</Badge>
          <div className="row-actions" onClick={(event) => event.stopPropagation()}>
            {document.status === 'failed' && <Button variant="ghost" size="icon" title="重试" onClick={() => onRetry(document.id)}><RefreshCw size={15} /></Button>}
            <Button variant="ghost" size="icon" title="删除" disabled={document.status === 'deleting'} onClick={() => onDelete(document.id)}><Trash2 size={15} /></Button>
          </div>
          <MoreHorizontal className="row-cue" size={16} />
        </article>
      ))}
    </div>
  )
}
