// report-generator.jsx — Report Generator (daftar permintaan laporan)
function ReportGeneratorPage({ merchants, primary, secondary, role = 'super', user }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const isMerchant = role === 'merchant';
  const requesterName = (user && user.name) || (isMerchant ? 'Rangga Pratama' : 'Arief Budiman');

  // Report types vary by role
  const REPORT_TYPES = isMerchant
    ? [
        { id: 'settlement', label: 'Laporan Settlement', icon: 'bx-wallet' },
        { id: 'transaction', label: 'Laporan Transaksi QRIS', icon: 'bx-transfer' },
        { id: 'refund', label: 'Laporan Refund', icon: 'bx-undo' },
        { id: 'disbursement', label: 'Laporan Pencairan Dana', icon: 'bx-money-withdraw' },
      ]
    : [
        { id: 'settlement', label: 'Laporan Recon & Settlement', icon: 'bx-receipt' },
        { id: 'disbursement', label: 'Laporan Disbursement', icon: 'bx-money-withdraw' },
        { id: 'transaction', label: 'Laporan Transaksi QRIS', icon: 'bx-transfer' },
        { id: 'onboarding', label: 'Laporan Onboarding Merchant', icon: 'bx-store' },
        { id: 'fds', label: 'Laporan Fraud Detection (FDS)', icon: 'bx-shield-quarter' },
        { id: 'refund', label: 'Laporan Refund', icon: 'bx-undo' },
      ];

  const typeLabel = (id) => (REPORT_TYPES.find(t => t.id === id) || {}).label || id;

  // Seed report requests
  const seedRequests = isMerchant
    ? [
        { id: 'RPT-2606-0042', type: 'settlement', period: '01 Jun 2026 – 24 Jun 2026', format: 'Excel', by: requesterName, at: '2026-06-24T09:12:00', status: 'completed', size: '248 KB', rows: 1247 },
        { id: 'RPT-2606-0039', type: 'transaction', period: '01 Jun 2026 – 23 Jun 2026', format: 'CSV', by: requesterName, at: '2026-06-23T16:40:00', status: 'completed', size: '1.4 MB', rows: 5820 },
        { id: 'RPT-2606-0036', type: 'refund', period: 'Mei 2026', format: 'PDF', by: requesterName, at: '2026-06-22T11:05:00', status: 'processing', size: '—', rows: null },
        { id: 'RPT-2605-0090', type: 'settlement', period: 'Mei 2026', format: 'Excel', by: requesterName, at: '2026-06-01T08:00:00', status: 'completed', size: '212 KB', rows: 1102 },
      ]
    : [
        { id: 'RPT-2606-0051', type: 'settlement', period: '24 Jun 2026', format: 'Excel', by: requesterName, at: '2026-06-24T10:30:00', status: 'completed', size: '512 KB', rows: 1250 },
        { id: 'RPT-2606-0050', type: 'transaction', period: '01 Jun 2026 – 24 Jun 2026', format: 'CSV', by: requesterName, at: '2026-06-24T10:02:00', status: 'processing', size: '—', rows: null },
        { id: 'RPT-2606-0048', type: 'disbursement', period: '23 Jun 2026', format: 'Excel', by: 'Dewi Anggraini', at: '2026-06-23T17:20:00', status: 'completed', size: '188 KB', rows: 312 },
        { id: 'RPT-2606-0047', type: 'fds', period: 'Q2 2026', format: 'PDF', by: 'Arief Budiman', at: '2026-06-23T14:15:00', status: 'queued', size: '—', rows: null },
        { id: 'RPT-2606-0044', type: 'onboarding', period: 'Jun 2026', format: 'Excel', by: 'Dewi Anggraini', at: '2026-06-22T09:40:00', status: 'failed', size: '—', rows: null, failReason: 'Sumber data onboarding tidak tersedia (timeout).' },
        { id: 'RPT-2605-0210', type: 'settlement', period: 'Mei 2026', format: 'Excel', by: 'Arief Budiman', at: '2026-06-01T08:05:00', status: 'completed', size: '1.1 MB', rows: 28140 },
      ];

  const [requests, setRequests] = React.useState(seedRequests);
  const [showModal, setShowModal] = React.useState(false);
  const [filter, setFilter] = React.useState('all');
  const [toast, setToast] = React.useState(null);

  // Form state
  const [fType, setFType] = React.useState(REPORT_TYPES[0].id);
  const [fStart, setFStart] = React.useState('2026-06-01');
  const [fEnd, setFEnd] = React.useState('2026-06-24');
  const [fFormat, setFFormat] = React.useState('Excel');

  const triggerToast = (msg, kind = 'success') => {
    setToast({ msg, kind });
    setTimeout(() => setToast(null), 3000);
  };

  const fmtDate = (iso) => {
    const d = new Date(iso);
    return d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }) + ' ' +
      d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });
  };

  const fmtPeriod = (s, e) => {
    const f = (iso) => new Date(iso).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });
    return s === e ? f(s) : `${f(s)} – ${f(e)}`;
  };

  const STATUS = {
    completed: { label: 'Selesai', color: GREEN, bg: 'rgba(116,181,12,0.12)', icon: 'bx-check-circle' },
    processing: { label: 'Diproses', color: TEAL, bg: 'rgba(0,86,210,0.10)', icon: 'bx-loader bx-spin' },
    queued: { label: 'Antrean', color: AMBER, bg: 'rgba(217,146,11,0.12)', icon: 'bx-time-five' },
    failed: { label: 'Gagal', color: RED, bg: 'rgba(237,49,81,0.10)', icon: 'bx-x-circle' },
  };

  const counts = {
    total: requests.length,
    completed: requests.filter(r => r.status === 'completed').length,
    processing: requests.filter(r => r.status === 'processing' || r.status === 'queued').length,
    failed: requests.filter(r => r.status === 'failed').length,
  };

  const visible = requests.filter(r => filter === 'all' || r.status === filter);

  const handleGenerate = (e) => {
    e.preventDefault();
    const newId = 'RPT-2606-' + Math.floor(1000 + Math.random() * 9000);
    const newReq = {
      id: newId, type: fType, period: fmtPeriod(fStart, fEnd), format: fFormat,
      by: requesterName, at: new Date().toISOString(), status: 'processing', size: '—', rows: null,
    };
    setRequests(prev => [newReq, ...prev]);
    setShowModal(false);
    triggerToast(`Permintaan laporan ${newId} sedang diproses...`, 'info');

    setTimeout(() => {
      setRequests(prev => prev.map(r => {
        if (r.id !== newId) return r;
        const rows = Math.floor(300 + Math.random() * 5000);
        const kb = Math.floor(120 + Math.random() * 900);
        return { ...r, status: 'completed', rows, size: kb > 1024 ? (kb / 1024).toFixed(1) + ' MB' : kb + ' KB' };
      }));
      triggerToast(`Laporan ${newId} selesai dibuat & siap diunduh.`, 'success');
    }, 2200);
  };

  const handleDownload = (r) => triggerToast(`Mengunduh ${r.id} (${typeLabel(r.type)}) — ${r.format}.`, 'success');
  const handleRetry = (id) => {
    setRequests(prev => prev.map(r => r.id === id ? { ...r, status: 'processing', failReason: null } : r));
    triggerToast('Memproses ulang permintaan laporan...', 'info');
    setTimeout(() => {
      setRequests(prev => prev.map(r => {
        if (r.id !== id) return r;
        const rows = Math.floor(300 + Math.random() * 5000);
        return { ...r, status: 'completed', rows, size: Math.floor(120 + Math.random() * 600) + ' KB' };
      }));
      triggerToast('Laporan berhasil dibuat ulang.', 'success');
    }, 2000);
  };

  const filterTabs = [
    { key: 'all', label: 'Semua', count: counts.total },
    { key: 'completed', label: 'Selesai', count: counts.completed },
    { key: 'processing', label: 'Diproses', count: requests.filter(r => r.status === 'processing').length },
    { key: 'queued', label: 'Antrean', count: requests.filter(r => r.status === 'queued').length },
    { key: 'failed', label: 'Gagal', count: counts.failed },
  ];

  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Report Generator</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Permintaan Laporan</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Daftar permintaan ekspor laporan. Buat permintaan baru, pantau status, dan unduh berkas yang telah selesai.</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms' }}
          onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
          onMouseLeave={e => e.currentTarget.style.background = TEAL}
        >
          <i className="bx bx-plus-circle" style={{ fontSize: 16 }} /> Buat Laporan Baru
        </button>
      </div>

      {/* Summary cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Permintaan', value: counts.total, sub: 'Semua laporan', icon: 'bx-folder', color: TEAL },
          { label: 'Selesai', value: counts.completed, sub: 'Siap diunduh', icon: 'bx-check-double', color: GREEN },
          { label: 'Dalam Proses', value: counts.processing, sub: 'Diproses / antrean', icon: 'bx-loader-circle', color: AMBER },
          { label: 'Gagal', value: counts.failed, sub: 'Perlu diproses ulang', icon: 'bx-error-circle', color: counts.failed > 0 ? RED : '#a7a8a8' }
        ].map((card, i) => (
          <div key={i} style={{ background: '#fff', padding: '18px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 200 }}>
            <div style={{ width: 44, height: 44, borderRadius: '50%', background: `${card.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`bx ${card.icon}`} style={{ fontSize: 20, color: card.color }} />
            </div>
            <div>
              <div style={{ fontSize: 12, color: '#a7a8a8', fontWeight: 600 }}>{card.label}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: '#171919', marginTop: 4, lineHeight: 1 }}>{card.value}</div>
              <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {filterTabs.map(t => {
          const active = filter === t.key;
          return (
            <button key={t.key} onClick={() => setFilter(t.key)}
              style={{
                border: active ? `1.5px solid ${TEAL}` : '1.5px solid #efefef',
                background: active ? `${TEAL}0d` : '#fff', color: active ? TEAL : '#515252',
                borderRadius: 100, padding: '7px 14px', fontSize: 12.5, fontWeight: 700, cursor: 'pointer',
                fontFamily: 'inherit', transition: 'all 150ms'
              }}>
              {t.label} <span style={{ opacity: 0.6 }}>({t.count})</span>
            </button>
          );
        })}
      </div>

      {/* Requests table */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
          <thead>
            <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 140 }}>ID Laporan</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Jenis Laporan</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Periode</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Format</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Diminta Oleh</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu Permintaan</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center', width: 150 }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {visible.length === 0 ? (
              <tr>
                <td colSpan="8" style={{ padding: '40px 20px', textAlign: 'center', color: '#a7a8a8' }}>
                  <i className="bx bx-folder-open" style={{ fontSize: 32, display: 'block', marginBottom: 8 }} />
                  Tidak ada permintaan laporan pada filter ini.
                </td>
              </tr>
            ) : visible.map(r => {
              const st = STATUS[r.status];
              return (
                <tr key={r.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '14px 20px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{r.id}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <div style={{ fontWeight: 700, color: '#171919' }}>{typeLabel(r.type)}</div>
                    {r.rows != null && <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{r.rows.toLocaleString('id-ID')} baris · {r.size}</div>}
                    {r.status === 'failed' && r.failReason && <div style={{ fontSize: 11, color: RED, marginTop: 2 }}>{r.failReason}</div>}
                  </td>
                  <td style={{ padding: '14px 20px', color: '#515252' }}>{r.period}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <span style={{ display: 'inline-block', background: '#f0f4fa', color: TEAL, fontSize: 11, fontWeight: 700, borderRadius: 4, padding: '3px 8px' }}>{r.format}</span>
                  </td>
                  <td style={{ padding: '14px 20px', color: '#515252' }}>{r.by}</td>
                  <td style={{ padding: '14px 20px', color: '#a7a8a8' }}>{fmtDate(r.at)}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: st.bg, color: st.color, fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 9px' }}>
                      <i className={`bx ${st.icon}`} /> {st.label}
                    </span>
                  </td>
                  <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                    {r.status === 'completed' && (
                      <button onClick={() => handleDownload(r)}
                        style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '7px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, boxShadow: `0 2px 6px ${TEAL}15`, fontFamily: 'inherit' }}>
                        <i className="bx bx-download" /> Unduh
                      </button>
                    )}
                    {(r.status === 'processing' || r.status === 'queued') && (
                      <span style={{ fontSize: 11.5, color: '#a7a8a8', fontStyle: 'italic' }}>Menunggu...</span>
                    )}
                    {r.status === 'failed' && (
                      <button onClick={() => handleRetry(r.id)}
                        style={{ background: '#fff', color: ORANGE, border: `1.5px solid ${ORANGE}`, borderRadius: 6, padding: '6px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'inherit' }}>
                        <i className="bx bx-refresh" /> Ulangi
                      </button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Modal: Create report request */}
      {showModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setShowModal(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(2px)' }} />
          <div style={{ position: 'relative', width: 480, background: '#fff', borderRadius: 14, boxShadow: '0 12px 36px rgba(23,25,25,0.15)', padding: '24px', animation: 'fadeIn 180ms ease' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #efefef', paddingBottom: 12, marginBottom: 16 }}>
              <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', margin: 0 }}>Buat Permintaan Laporan</h3>
              <button onClick={() => setShowModal(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 20 }} /></button>
            </div>

            <form onSubmit={handleGenerate}>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Jenis Laporan</label>
                <select value={fType} onChange={e => setFType(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', background: '#fff', fontFamily: 'inherit' }}>
                  {REPORT_TYPES.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
                </select>
              </div>

              <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Tanggal Mulai</label>
                  <input type="date" value={fStart} onChange={e => setFStart(e.target.value)}
                    style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Tanggal Akhir</label>
                  <input type="date" value={fEnd} onChange={e => setFEnd(e.target.value)}
                    style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit' }} />
                </div>
              </div>

              <div style={{ marginBottom: 22 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 8 }}>Format Berkas</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {['Excel', 'CSV', 'PDF'].map(fmt => {
                    const active = fFormat === fmt;
                    return (
                      <button key={fmt} type="button" onClick={() => setFFormat(fmt)}
                        style={{ flex: 1, padding: '10px 0', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                          border: active ? `1.5px solid ${TEAL}` : '1.5px solid #efefef', background: active ? `${TEAL}0d` : '#fff', color: active ? TEAL : '#515252' }}>
                        {fmt}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setShowModal(false)} style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '9px 16px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer' }}>Batal</button>
                <button type="submit" style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', boxShadow: '0 4px 12px rgba(0,86,210,0.15)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <i className="bx bx-cog" /> Proses Laporan
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 24, right: 24, zIndex: 1600,
          background: toast.kind === 'info' ? TEAL : (toast.kind === 'error' ? RED : '#10B981'),
          color: '#fff', padding: '16px 24px', borderRadius: 10,
          boxShadow: '0 8px 24px rgba(16,185,129,0.25)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease'
        }}>
          <i className={`bx ${toast.kind === 'info' ? 'bx-loader bx-spin' : (toast.kind === 'error' ? 'bx-x-circle' : 'bx-check-shield')}`} style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 750 }}>{toast.msg}</span>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ReportGeneratorPage });
