import { FileUp, LoaderCircle } from 'lucide-react'
import { useRef, useState } from 'react'

import { Button } from '../../components/ui/button'
import { uploadDocument } from './api'

type Props = { onUploaded: (documentId: string) => void }

export function UploadDocument({ onUploaded }: Props) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleFile(file?: File) {
    if (!file) return
    setUploading(true)
    setError(null)
    try {
      const document = await uploadDocument(file)
      onUploaded(document.id)
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : '上传失败')
    } finally {
      setUploading(false)
      if (inputRef.current) inputRef.current.value = ''
    }
  }

  return (
    <div className="upload-control">
      <input ref={inputRef} className="sr-only" type="file" accept=".pdf,.md,.markdown,.txt" onChange={(event) => void handleFile(event.target.files?.[0])} />
      <Button onClick={() => inputRef.current?.click()} disabled={uploading}>
        {uploading ? <LoaderCircle className="spin" size={16} /> : <FileUp size={16} />}
        {uploading ? '正在上传' : '上传文档'}
      </Button>
      {error && <p className="inline-error" role="alert">{error}</p>}
    </div>
  )
}
