import { useRef, useState } from 'react'
import { uploadSeed, type SeedReport } from '../api/client'
import HelpButton from '../help/HelpButton'

export default function SeedUpload({ onUploaded }: { onUploaded: () => void }) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [report, setReport] = useState<SeedReport | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  async function handle(file: File) {
    setError(null)
    setBusy(true)
    try {
      setReport(await uploadSeed(file))
      onUploaded()
    } catch (e) {
      setError((e as Error).message)
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="border-t border-gray-200 p-3">
      <input
        ref={inputRef}
        type="file"
        accept=".xlsx,.xlsm"
        className="hidden"
        onChange={(e) => {
          const file = e.target.files?.[0]
          if (file) void handle(file)
          e.target.value = ''
        }}
      />
      <button
        type="button"
        disabled={busy}
        onClick={() => inputRef.current?.click()}
        className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm disabled:opacity-50"
      >
        신청목록 시트 올리기
      </button>
      <span className="mt-2 flex items-center justify-center gap-1 text-xs text-gray-400">
        업로드 방법
        <HelpButton topic="channel.seed" />
      </span>

      {report && (
        <p className="mt-2 text-xs text-gray-500">
          신규 {report.created} / 갱신 {report.updated} / 전체 {report.total}
        </p>
      )}
      {error && <p className="mt-2 text-xs text-red-600">{error}</p>}
    </div>
  )
}
