/* Bulk Operations — net-new in the prototype idiom (no prototype counterpart).
   Wires to existing /api/bulk routes:
     GET  /api/bulk/species/export    → CSV download
     POST /api/bulk/species/import    → CSV upload (text/csv body)
     POST /api/bulk/zones/:id/assign  → bulk-assign species to a zone */

function BulkScreen() {
  const [importStatus, setImportStatus] = useState(null);
  const fileRef = useRef(null);

  async function handleExport() {
    const token = Auth.getToken();
    try {
      const res = await fetch('/api/bulk/species/export', {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      });
      if (!res.ok) throw new Error(await res.text());
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `species-export-${new Date().toISOString().slice(0, 10)}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (err) {
      setImportStatus({ kind: 'error', msg: 'Export failed: ' + err.message });
    }
  }

  async function handleImport(file) {
    if (!file) return;
    setImportStatus({ kind: 'pending', msg: `Uploading ${file.name}…` });
    try {
      const text = await file.text();
      const res = await fetch('/api/bulk/species/import', {
        method: 'POST',
        headers: {
          'Content-Type': 'text/csv',
          ...(Auth.getToken() ? { Authorization: `Bearer ${Auth.getToken()}` } : {}),
        },
        body: text,
      });
      const body = await res.json();
      if (!res.ok) throw new Error(body.error || 'Import failed');
      setImportStatus({
        kind: 'ok',
        msg: `Imported ${body.imported || 0} species · ${body.skipped || 0} skipped`,
      });
    } catch (err) {
      setImportStatus({ kind: 'error', msg: err.message });
    }
  }

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 880 }}>
        <header style={{ marginBottom: 24 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>Tools</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>Bulk operations</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            CSV import and export for species data, plus zone assignment in bulk.
          </p>
        </header>

        <section className="x-card" style={{ padding: 22, marginBottom: 14 }}>
          <div className="x-eyebrow">Export</div>
          <h2 style={{
            margin: '4px 0 6px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 16, fontWeight: 500, color: 'var(--aq-text)',
          }}>Download species library as CSV</h2>
          <p style={{ fontSize: 12.5, color: 'var(--aq-text-faint)', margin: '0 0 12px' }}>
            Includes every species in the global library — 26 columns covering taxonomy, IUCN status, descriptions, and accent colours.
          </p>
          <button className="x-btn" onClick={handleExport}>
            <Icon name="library" size={12} />Export species.csv
          </button>
        </section>

        <section className="x-card" style={{ padding: 22, marginBottom: 14 }}>
          <div className="x-eyebrow">Import</div>
          <h2 style={{
            margin: '4px 0 6px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 16, fontWeight: 500, color: 'var(--aq-text)',
          }}>Upload species CSV</h2>
          <p style={{ fontSize: 12.5, color: 'var(--aq-text-faint)', margin: '0 0 12px' }}>
            Header row is required. Existing species (matched by scientific_name) are updated. New rows are inserted. Max 5 MB.
          </p>
          <input
            ref={fileRef}
            type="file"
            accept=".csv,text/csv"
            onChange={(e) => handleImport(e.target.files && e.target.files[0])}
            style={{ display: 'none' }}
          />
          <button
            className="x-btn"
            onClick={() => fileRef.current && fileRef.current.click()}
          >
            <Icon name="plus" size={12} />Choose CSV…
          </button>
          {importStatus && (
            <div style={{
              marginTop: 12, padding: '8px 12px', borderRadius: 6, fontSize: 12,
              background: importStatus.kind === 'error'
                ? 'color-mix(in srgb, var(--aq-danger) 12%, transparent)'
                : importStatus.kind === 'ok'
                  ? 'color-mix(in srgb, var(--aq-success) 12%, transparent)'
                  : 'var(--aq-surface-2)',
              border: `1px solid ${importStatus.kind === 'error'
                ? 'color-mix(in srgb, var(--aq-danger) 30%, transparent)'
                : importStatus.kind === 'ok'
                  ? 'color-mix(in srgb, var(--aq-success) 30%, transparent)'
                  : 'var(--aq-line)'}`,
              color: importStatus.kind === 'error'
                ? 'var(--aq-danger)'
                : importStatus.kind === 'ok'
                  ? 'var(--aq-success)'
                  : 'var(--aq-text-muted)',
            }}>{importStatus.msg}</div>
          )}
        </section>

        <section className="x-card" style={{ padding: 22 }}>
          <div className="x-eyebrow">Zone assignment</div>
          <h2 style={{
            margin: '4px 0 6px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 16, fontWeight: 500, color: 'var(--aq-text)',
          }}>Bulk-assign species to a zone</h2>
          <p style={{ fontSize: 12.5, color: 'var(--aq-text-faint)', margin: '0 0 12px' }}>
            Use the <a style={{ color: 'var(--aq-accent)', cursor: 'pointer' }} onClick={() => { window.location.hash = '#zones'; }}>Zones</a> page to add species to individual zones, or call POST /api/bulk/zones/:id/assign with a species_ids array directly.
          </p>
          <button
            className="x-btn ghost"
            onClick={() => { window.location.hash = '#zones'; }}
          >
            <Icon name="building" size={12} />Open zones
          </button>
        </section>
      </div>
    </div>
  );
}

window.BulkScreen = BulkScreen;
