// AuditReportsScreen.jsx — AegisComply
// Lists every audit report ever generated (PPE / Calibration / etc.) for
// this account. Data source = public.documents rows where category='audit'.
// PDFReports.jsx auto-files reports here whenever the user exports one, so
// this screen is the single place to browse, download or delete them.

const AUDIT_TYPES = {
  ppe_audit: {
    label: 'PPE Stock Audit',
    short: 'PPE',
    color: '#0D9488',
    bg:    '#F0FDFA',
    icon: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/>
      </svg>
    ),
  },
  calibration_audit: {
    label: 'Calibration Audit',
    short: 'CAL',
    color: '#9333EA',
    bg:    '#FAF5FF',
    icon: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
      </svg>
    ),
  },
  upload: {
    label: 'Uploaded Report',
    short: 'UPL',
    color: '#64748B',
    bg:    '#F1F5F9',
    icon: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
      </svg>
    ),
  },
};

function detectAuditType(doc) {
  const src = (doc.source || '').toLowerCase();
  if (src.includes('ppe'))         return 'ppe_audit';
  if (src.includes('calibration')) return 'calibration_audit';
  const tags = (doc.tags || []).join(' ').toLowerCase();
  if (tags.includes('ppe'))         return 'ppe_audit';
  if (tags.includes('calibration')) return 'calibration_audit';
  return 'upload';
}

function fmtAuditDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return d; }
}
function fmtAuditDateTime(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }
  catch { return d; }
}
function fmtAuditBytes(n) {
  if (!n) return '—';
  if (n < 1024) return n + ' B';
  if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  return (n / (1024 * 1024)).toFixed(1) + ' MB';
}

const arStyles = {
  page:       { padding: 24 },
  kpis:       { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 22 },
  kpiCard:    { background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, padding: '14px 16px', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' },
  kpiLabel:   { fontSize: 11, fontWeight: 600, color: '#64748B', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 },
  kpiValue:   { fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 24, fontWeight: 700, color: '#0F172A', lineHeight: 1.1 },
  kpiSub:     { fontSize: 11, color: '#94A3B8', marginTop: 4 },

  toolbar:    { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, flexWrap: 'wrap' },
  searchWrap: { position: 'relative', flex: 1, maxWidth: 320 },
  searchInput:{ width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 12px 0 36px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#334155', outline: 'none', background: 'white' },
  searchIcon: { position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: '#94A3B8', pointerEvents: 'none' },
  filterPill: { height: 36, padding: '0 14px', border: '1px solid #CBD5E1', borderRadius: 18, fontSize: 12, fontWeight: 600, color: '#475569', background: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", display: 'flex', alignItems: 'center', gap: 6 },
  filterPillActive: { background: '#0F172A', color: 'white', borderColor: '#0F172A' },
  generateBtn:{ height: 36, padding: '0 16px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 600, color: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'DM Sans',sans-serif", marginLeft: 'auto' },
  generateBtnDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },

  tableCard:  { background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' },
  table:      { width: '100%', borderCollapse: 'collapse', fontSize: 13 },
  th:         { textAlign: 'left', padding: '12px 14px', fontSize: 11, fontWeight: 700, color: '#64748B', letterSpacing: '0.04em', textTransform: 'uppercase', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' },
  td:         { padding: '12px 14px', borderBottom: '1px solid #F1F5F9', color: '#334155', verticalAlign: 'middle' },
  rowHover:   { background: '#F8FAFC' },
  typeBadge:  { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 100, fontSize: 11, fontWeight: 700 },
  sourceTag:  { fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: '#F0FDFA', color: '#0D9488', letterSpacing: '0.04em', textTransform: 'uppercase' },
  sourceTagUpload: { background: '#F1F5F9', color: '#64748B' },
  iconBtn:    { width: 30, height: 30, borderRadius: 6, border: '1px solid #E2E8F0', background: 'white', color: '#475569', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transition: 'all 150ms' },
  iconBtnDanger: { borderColor: '#FECACA', color: '#DC2626' },

  empty:      { padding: 60, textAlign: 'center', border: '2px dashed #E2E8F0', borderRadius: 12, background: 'white' },
  emptyIcon:  { width: 60, height: 60, borderRadius: 12, background: '#F1F5F9', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14, color: '#94A3B8' },
  emptyTitle: { fontSize: 16, fontWeight: 700, color: '#334155', marginBottom: 6 },
  emptySub:   { fontSize: 13, color: '#94A3B8', marginBottom: 18, maxWidth: 420, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.5 },

  errorBox:   { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '10px 14px', fontSize: 12, color: '#DC2626', marginBottom: 14 },
};

function AuditReportsScreen({ user, isFrozen, onGenerate }) {
  const [reports, setReports]   = React.useState([]);
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState('');
  const [search, setSearch]     = React.useState('');
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [hovered, setHovered]   = React.useState(null);

  const fetchReports = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { data, error: qErr } = await sb
        .from('documents')
        .select('*')
        .eq('category', 'audit')
        .order('created_at', { ascending: false });
      if (qErr) throw qErr;
      setReports(data || []);
    } catch (err) {
      console.error('[AuditReports] fetch error:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { fetchReports(); }, [fetchReports]);

  // Live updates — whenever PDFReports.jsx inserts a new audit row, refresh.
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`audit-reports-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'documents', filter: `user_id=eq.${user.id}` }, () => fetchReports())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchReports]);

  const enriched = React.useMemo(() => reports.map(r => ({ ...r, _type: detectAuditType(r) })), [reports]);

  const counts = React.useMemo(() => {
    const c = { all: enriched.length, ppe_audit: 0, calibration_audit: 0, upload: 0 };
    enriched.forEach(r => { c[r._type]++; });
    return c;
  }, [enriched]);

  const visible = React.useMemo(() => {
    const t = search.trim().toLowerCase();
    return enriched.filter(r => {
      if (typeFilter !== 'all' && r._type !== typeFilter) return false;
      if (t) {
        const hay = `${r.name || ''} ${r.description || ''} ${(r.tags || []).join(' ')}`.toLowerCase();
        if (!hay.includes(t)) return false;
      }
      return true;
    });
  }, [enriched, search, typeFilter]);

  const lastGenerated = enriched.find(r => r.source && r.source.startsWith('auto:'))?.created_at || enriched[0]?.created_at;

  const handleDownload = async (r) => {
    try {
      const sb = window.supabaseClient;
      const { data, error: urlErr } = await sb.storage.from('documents').createSignedUrl(r.file_path, 60);
      if (urlErr) throw urlErr;
      window.open(data.signedUrl, '_blank');
    } catch (err) {
      alert('Download failed: ' + err.message);
    }
  };

  const handleDelete = async (r) => {
    if (!window.confirm(`Delete this audit report?\n\n${r.name}\n\nThis cannot be undone.`)) return;
    try {
      const sb = window.supabaseClient;
      try { await sb.storage.from('documents').remove([r.file_path]); } catch (_) {}
      const { error: delErr } = await sb.from('documents').delete().eq('id', r.id);
      if (delErr) throw delErr;
      fetchReports();
    } catch (err) {
      alert('Delete failed: ' + err.message);
    }
  };

  return (
    <div style={arStyles.page}>
      {/* KPIs */}
      <div style={arStyles.kpis}>
        <div style={arStyles.kpiCard}>
          <div style={arStyles.kpiLabel}>Total Reports</div>
          <div style={arStyles.kpiValue}>{counts.all}</div>
          <div style={arStyles.kpiSub}>across all audit types</div>
        </div>
        <div style={arStyles.kpiCard}>
          <div style={arStyles.kpiLabel}>PPE Audits</div>
          <div style={{ ...arStyles.kpiValue, color: AUDIT_TYPES.ppe_audit.color }}>{counts.ppe_audit}</div>
          <div style={arStyles.kpiSub}>stock + issuance history</div>
        </div>
        <div style={arStyles.kpiCard}>
          <div style={arStyles.kpiLabel}>Calibration Audits</div>
          <div style={{ ...arStyles.kpiValue, color: AUDIT_TYPES.calibration_audit.color }}>{counts.calibration_audit}</div>
          <div style={arStyles.kpiSub}>equipment certificates</div>
        </div>
        <div style={arStyles.kpiCard}>
          <div style={arStyles.kpiLabel}>Last Generated</div>
          <div style={{ ...arStyles.kpiValue, fontSize: 15 }}>{lastGenerated ? fmtAuditDate(lastGenerated) : '—'}</div>
          <div style={arStyles.kpiSub}>{lastGenerated ? fmtAuditDateTime(lastGenerated) : 'No reports yet'}</div>
        </div>
      </div>

      {/* Toolbar */}
      <div style={arStyles.toolbar}>
        <div style={arStyles.searchWrap}>
          <svg style={arStyles.searchIcon} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input style={arStyles.searchInput} placeholder="Search reports…" value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        {[
          { id: 'all',               label: `All (${counts.all})` },
          { id: 'ppe_audit',         label: `PPE (${counts.ppe_audit})` },
          { id: 'calibration_audit', label: `Calibration (${counts.calibration_audit})` },
          { id: 'upload',            label: `Uploaded (${counts.upload})` },
        ].map(p => (
          <button
            key={p.id}
            style={{ ...arStyles.filterPill, ...(typeFilter === p.id ? arStyles.filterPillActive : {}) }}
            onClick={() => setTypeFilter(p.id)}
          >{p.label}</button>
        ))}
        <button
          style={{ ...arStyles.generateBtn, ...(isFrozen ? arStyles.generateBtnDisabled : {}) }}
          onClick={() => !isFrozen && onGenerate && onGenerate()}
          disabled={isFrozen}
          title={isFrozen ? 'Frozen — renew to generate' : 'Generate a new audit report'}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Generate New Report
        </button>
      </div>

      {error && <div style={arStyles.errorBox}>{error}</div>}

      {loading && reports.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8' }}>Loading audit reports…</div>
      ) : visible.length === 0 ? (
        <div style={arStyles.empty}>
          <div style={arStyles.emptyIcon}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
          </div>
          <div style={arStyles.emptyTitle}>
            {search || typeFilter !== 'all' ? 'No reports match your filters' : 'No audit reports yet'}
          </div>
          <div style={arStyles.emptySub}>
            {search || typeFilter !== 'all'
              ? 'Try clearing the filters above.'
              : 'Generate a PPE Stock Audit or Calibration Audit from the Dashboard, or click "Generate New Report" above — it will be saved here automatically.'}
          </div>
          {!search && typeFilter === 'all' && !isFrozen && (
            <button style={arStyles.generateBtn} onClick={() => onGenerate && onGenerate()}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              Generate your first report
            </button>
          )}
        </div>
      ) : (
        <div style={arStyles.tableCard}>
          <table style={arStyles.table}>
            <thead>
              <tr>
                <th style={arStyles.th}>Report</th>
                <th style={arStyles.th}>Type</th>
                <th style={arStyles.th}>Source</th>
                <th style={{ ...arStyles.th, textAlign: 'right' }}>Size</th>
                <th style={arStyles.th}>Generated</th>
                <th style={{ ...arStyles.th, textAlign: 'right' }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {visible.map((r, i) => {
                const t = AUDIT_TYPES[r._type] || AUDIT_TYPES.upload;
                const IconC = t.icon;
                const isAuto = (r.source || '').startsWith('auto:');
                return (
                  <tr
                    key={r.id}
                    style={hovered === i ? arStyles.rowHover : undefined}
                    onMouseEnter={() => setHovered(i)}
                    onMouseLeave={() => setHovered(null)}
                  >
                    <td style={arStyles.td}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div style={{ width: 34, height: 34, borderRadius: 8, background: t.bg, color: t.color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                          <IconC/>
                        </div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A', lineHeight: 1.3 }}>{r.name}</div>
                          {r.description && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2, lineHeight: 1.4 }}>{r.description.length > 80 ? r.description.slice(0, 80) + '…' : r.description}</div>}
                        </div>
                      </div>
                    </td>
                    <td style={arStyles.td}>
                      <span style={{ ...arStyles.typeBadge, background: t.bg, color: t.color }}>{t.label}</span>
                    </td>
                    <td style={arStyles.td}>
                      <span style={{ ...arStyles.sourceTag, ...(isAuto ? {} : arStyles.sourceTagUpload) }}>{isAuto ? 'Auto' : 'Manual'}</span>
                    </td>
                    <td style={{ ...arStyles.td, textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#64748B' }}>{fmtAuditBytes(r.file_size)}</td>
                    <td style={arStyles.td}>
                      <div style={{ fontSize: 12, color: '#334155' }}>{fmtAuditDate(r.created_at)}</div>
                      <div style={{ fontSize: 10, color: '#94A3B8' }}>{fmtAuditDateTime(r.created_at)}</div>
                    </td>
                    <td style={{ ...arStyles.td, textAlign: 'right' }}>
                      <button
                        style={arStyles.iconBtn}
                        title="Download"
                        onClick={() => handleDownload(r)}
                        onMouseEnter={e => { e.currentTarget.style.background = '#F0FDFA'; e.currentTarget.style.color = '#0D9488'; e.currentTarget.style.borderColor = '#A7F3D0'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = '#475569'; e.currentTarget.style.borderColor = '#E2E8F0'; }}
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                      </button>
                      <button
                        style={{ ...arStyles.iconBtn, ...arStyles.iconBtnDanger, marginLeft: 6 }}
                        title="Delete"
                        onClick={() => !isFrozen && handleDelete(r)}
                        disabled={isFrozen}
                      >
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"/></svg>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AuditReportsScreen });
