'use client'

// Replace the ALT or NEU file of a comparison (KAR-845 part 2): pick a file,
// upload via signed URL, then replaceComparisonFile re-ingests and recomputes.
// tdd-guard:skip — thin upload/action trigger; ingest + recompare are tested
// server-side.

import { useRef, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { FileUp } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { createQafUploadTargets } from '@/app/qaf-differences/actions'
import { replaceComparisonFile } from '@/app/qaf-differences/file-replace-actions'
import { uploadWithProgress } from '@/components/qaf-differences/qaf-upload-constants'

interface Props {
  comparisonId: string
  projectId: string
  role: 'alt' | 'neu'
}

export default function QafReplaceFileButton({ comparisonId, projectId, role }: Props) {
  const router = useRouter()
  const inputRef = useRef<HTMLInputElement>(null)
  const [pending, startTransition] = useTransition()
  const [error, setError] = useState<string | null>(null)

  function onPick(file: File | undefined) {
    if (!file) return
    setError(null)
    startTransition(async () => {
      try {
        const targets = await createQafUploadTargets(projectId, [{ name: file.name, size: file.size }])
        if (!targets.ok) return setError(targets.error)
        await uploadWithProgress(targets.data[0].signedUrl, file, () => {})
        const res = await replaceComparisonFile(comparisonId, role, {
          path: targets.data[0].path,
          name: file.name,
        })
        if (res.ok) {
          router.refresh()
        } else {
          setError(res.error)
        }
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Ersetzen fehlgeschlagen.')
      }
    })
  }

  return (
    <span className="inline-flex items-center gap-2">
      <input
        ref={inputRef}
        type="file"
        accept=".xlsx,.xlsm,.xls"
        className="hidden"
        onChange={(e) => {
          onPick(e.target.files?.[0])
          e.target.value = ''
        }}
      />
      <Button onClick={() => inputRef.current?.click()} disabled={pending} variant="outline" size="sm">
        <FileUp size={14} />
        {pending ? 'Ersetze …' : role === 'alt' ? 'ALT-Datei ersetzen' : 'NEU-Datei ersetzen'}
      </Button>
      {error && <span className="max-w-72 text-xs text-destructive">{error}</span>}
    </span>
  )
}
