import { useState, type ReactNode } from 'react';
import { downloadAuthedFile } from '../api/download';

type Props = {
  apiPath: string;
  filename: string;
  className?: string;
  children: ReactNode;
};

export default function AuthDownloadButton({ apiPath, filename, className, children }: Props) {
  const [busy, setBusy] = useState(false);

  const handleClick = async (e: React.MouseEvent) => {
    e.preventDefault();
    if (busy) return;
    setBusy(true);
    try {
      await downloadAuthedFile(apiPath, filename);
    } catch (err) {
      window.alert(err instanceof Error ? err.message : 'Download failed');
    } finally {
      setBusy(false);
    }
  };

  return (
    <button type="button" className={className} onClick={handleClick} disabled={busy}>
      {busy ? '…' : children}
    </button>
  );
}
