'use client';
import { useState } from 'react';
import { api } from '@/lib/api';

interface ImportResult {
  created: number;
  createdSubs?: number;
  failed: number;
  errors: { row: number; message: string }[];
}

/** CSV/XLSX bulk import box with template downloads and per-row error report. */
export function Importer({ kind, label, onDone }: { kind: 'users' | 'samples' | 'actions'; label?: string; onDone: () => void }) {
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState<ImportResult | null>(null);
  const [err, setErr] = useState('');
  const go = async (f: File) => {
    setBusy(true); setErr(''); setResult(null);
    const okExt = /\.(csv|xlsx)$/i.test(f.name);
    const okSize = f.size <= 10 * 1024 * 1024;
    if (!okExt) { setErr('Only CSV or Excel files (.csv, .xlsx) are accepted.'); setBusy(false); return; }
    if (!okSize) { setErr('File must be 10MB or smaller.'); setBusy(false); return; }
    try {
      const fd = new FormData();
      fd.append('file', f);
      const r = await api.upload(`/api/v1/imports/${kind}`, fd);
      setResult(r);
      if (r.created > 0) onDone();
    } catch (e: any) { setErr(e.message); }
    finally { setBusy(false); }
  };
  return (
    <div className="card space-y-2">
      <div className="flex flex-wrap gap-2 items-center">
        <b className="text-sm mr-auto">Bulk import {label ?? kind}</b>
        <button className="text-xs underline" onClick={() => api.download(`/api/v1/imports/${kind}/template?format=csv`, `${kind}-import-template.csv`)}>CSV template</button>
        <button className="text-xs underline" onClick={() => api.download(`/api/v1/imports/${kind}/template?format=xlsx`, `${kind}-import-template.xlsx`)}>Excel template</button>
        <label className="btn-ghost text-sm cursor-pointer">{busy ? 'Importing…' : 'Choose file'}
          <input type="file" className="hidden" accept=".csv,.xlsx" disabled={busy}
            onChange={(e) => { const f = e.target.files?.[0]; if (f) go(f); e.target.value = ''; }} />
        </label>
      </div>
      <p className="text-xs text-slate-500">Download the template, fill it in, then choose the file to import.</p>
      {err && <p className="text-sm text-red-600">{err}</p>}
      {result && (
        <div className="text-sm">
          <p><b className="text-green-700">{result.created} created{result.createdSubs != null ? ` (+${result.createdSubs} sub-actions)` : ''}</b> · <b className="text-red-700">{result.failed} failed</b></p>
          {!!result.errors.length && (
            <div className="max-h-40 overflow-y-auto border rounded mt-1">
              {result.errors.map((e, i) => <p key={i} className="text-xs border-t px-2 py-1">Row {e.row}: {e.message}</p>)}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
