// tdd-guard:skip — Client-Download-Button; die Export-Erzeugung (rehydrate +
// buildXxxExportWorkbook) ist server-seitig + unit-getestet, hier nur
// UI/Blob-Glue.
//
// Shared XLSX-export-button component (KAR-949 review Finding 3 — cleanup).
// Before this file existed, qaf-export-button.tsx (KAR-799),
// qaf-g60-export-button.tsx (KAR-913/P4.3), qaf-multi-qaf-export-button.tsx
// and qaf-variant-vs-standard-export-button.tsx (both KAR-949) were four
// byte-identical copies of this component (~70 lines each incl.
// base64ToBlob), differing only in which server action they call and the
// button label text. All four export server actions
// (exportQafComparisonXlsx / exportQafG60ComparisonXlsx /
// exportMultiQafComparisonXlsx / exportVariantVsStandardComparisonXlsx)
// share the exact same signature
// `(comparisonId: string, generatedAtLabel: string) =>
// Promise<ActionResult<QafExportDownload>>` (app/qaf-differences/actions.ts)
// — the download filename is always server-computed
// (`res.data.filename`), never client-supplied, so this component takes
// only the action + a button label, not a filename.
'use client'

import { useState } from 'react'
import { Download, Loader2 } from 'lucide-react'
import type { ActionResult } from '@/app/qaf-differences/actions'
import type { QafExportDownload } from '@/app/qaf-differences/actions'

export type QafXlsxExportAction = (
  comparisonId: string,
  generatedAtLabel: string,
) => Promise<ActionResult<QafExportDownload>>

export interface QafXlsxExportButtonProps {
  comparisonId: string
  /** One of the exportXxxComparisonXlsx server actions in actions.ts. */
  action: QafXlsxExportAction
  /** Button label while idle, e.g. "Excel-Export (8 Blatt)". */
  label: string
  /** Button label while the export is being generated. */
  busyLabel?: string
  className?: string
}

function base64ToBlob(base64: string, type: string): Blob {
  const bin = atob(base64)
  const bytes = new Uint8Array(bin.length)
  for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
  return new Blob([bytes], { type })
}

export default function QafXlsxExportButton({
  comparisonId,
  action,
  label,
  busyLabel = 'Erzeuge Excel…',
  className,
}: QafXlsxExportButtonProps) {
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleExport() {
    setBusy(true)
    setError(null)
    try {
      // Timestamp is formatted client-side so the engine stays Date-free.
      const generatedAtLabel = new Date().toLocaleString('de-DE')
      const res = await action(comparisonId, generatedAtLabel)
      if (!res.ok) {
        setError(res.error)
        return
      }
      const blob = base64ToBlob(
        res.data.base64,
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      )
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = res.data.filename
      document.body.appendChild(a)
      a.click()
      a.remove()
      setTimeout(() => URL.revokeObjectURL(url), 1000)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Export fehlgeschlagen.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className={className}>
      <button
        type="button"
        onClick={handleExport}
        disabled={busy}
        className="inline-flex items-center gap-1.5 rounded-sm border border-input bg-background px-3 py-1.5 text-sm text-foreground hover:bg-state-hover disabled:opacity-60"
      >
        {busy ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}
        {busy ? busyLabel : label}
      </button>
      {error && <p className="mt-1 text-xs text-destructive">{error}</p>}
    </div>
  )
}
