'use client';

import { useEffect, useRef, useState } from 'react';

const SINCE_OPTIONS = [
  { label: '1 hour', value: '1h' },
  { label: '1 day', value: '1d' },
  { label: '7 days', value: '7d' },
  { label: '30 days', value: '30d' },
];

function sinceToISO(val) {
  if (!val) return null;
  const now = Date.now();
  const map = { '1h': 3600, '1d': 86400, '7d': 604800, '30d': 2592000 };
  const secs = map[val];
  if (!secs) return null;
  return new Date(now - secs * 1000).toISOString();
}

function fmtTime(t) {
  if (!t) return '';
  try { return new Date(t).toLocaleString(); } catch { return String(t); }
}

function fmtBytes(n) {
  if (n == null) return '';
  if (n < 1024) return `${n} B`;
  if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / 1048576).toFixed(1)} MB`;
}

function ShieldIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
    </svg>
  );
}

function exportCSV(rows, columns, filename) {
  const header = columns.map(c => JSON.stringify(c.label)).join(',');
  const body = rows.map(row =>
    columns.map(c => {
      const v = c.get(row);
      return JSON.stringify(v == null ? '' : String(v));
    }).join(',')
  ).join('\n');
  const blob = new Blob([header + '\n' + body], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

const AUDIT_COLS = [
  { label: 'Time',    get: r => r.at },
  { label: 'Type',    get: r => r.type },
  { label: 'Summary', get: r => r.summary },
  { label: 'Status',  get: r => r.status },
  { label: 'Meta',    get: r => r.meta },
];

const EGRESS_COLS = [
  { label: 'Time',      get: r => r.at },
  { label: 'Tool',      get: r => r.tool_name },
  { label: 'Agent',     get: r => r.agent_id },
  { label: 'Host',      get: r => r.host },
  { label: 'Method',    get: r => r.method },
  { label: 'Status',    get: r => r.status_code },
  { label: 'Bytes In',  get: r => r.bytes_in },
  { label: 'Bytes Out', get: r => r.bytes_out },
  { label: 'ms',        get: r => r.duration_ms },
];

export default function AuditTab() {
  const [filterType, setFilterType] = useState('');
  const [filterAgent, setFilterAgent] = useState('');
  const [filterSince, setFilterSince] = useState('1d');
  const [types, setTypes] = useState([]);
  const [audit, setAudit] = useState([]);
  const [egress, setEgress] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const intervalRef = useRef(null);

  function buildUrl() {
    const p = new URLSearchParams();
    p.set('limit', '200');
    if (filterType) p.set('type', filterType);
    if (filterAgent) p.set('agent_id', filterAgent);
    const iso = sinceToISO(filterSince);
    if (iso) p.set('since', iso);
    return `/api/audit/list?${p}`;
  }

  async function load() {
    try {
      const res = await fetch(buildUrl());
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      setAudit(data.audit ?? []);
      setEgress(data.egress ?? []);
      if (data.types?.length) setTypes(data.types);
      setError(null);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    setLoading(true);
    load();
    intervalRef.current = setInterval(load, 10000);
    return () => clearInterval(intervalRef.current);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterType, filterAgent, filterSince]);

  return (
    <div>
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <ShieldIcon /> Live audit
          </span>
          <small>Auto-refreshes every 10 s. Showing up to 200 rows per table.</small>
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'flex-end', marginBottom: 14 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 11 }}>
            <span style={{ textTransform: 'uppercase', letterSpacing: '.08em', color: '#68707b' }}>Type</span>
            <select
              value={filterType}
              onChange={e => setFilterType(e.target.value)}
              style={{ fontSize: 12.5, padding: '5px 8px', borderRadius: 8, border: '1px solid rgba(17,19,24,.12)', background: '#fff' }}
            >
              <option value="">All</option>
              {types.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </label>

          <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 11 }}>
            <span style={{ textTransform: 'uppercase', letterSpacing: '.08em', color: '#68707b' }}>Agent ID</span>
            <input
              type="text"
              value={filterAgent}
              onChange={e => setFilterAgent(e.target.value)}
              placeholder="any"
              style={{ fontSize: 12.5, padding: '5px 8px', borderRadius: 8, border: '1px solid rgba(17,19,24,.12)', width: 160 }}
            />
          </label>

          <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 11 }}>
            <span style={{ textTransform: 'uppercase', letterSpacing: '.08em', color: '#68707b' }}>Since</span>
            <select
              value={filterSince}
              onChange={e => setFilterSince(e.target.value)}
              style={{ fontSize: 12.5, padding: '5px 8px', borderRadius: 8, border: '1px solid rgba(17,19,24,.12)', background: '#fff' }}
            >
              <option value="">All time</option>
              {SINCE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </label>

          <button
            onClick={() => { setLoading(true); load(); }}
            style={{ fontSize: 12.5, padding: '6px 14px', borderRadius: 8, border: '1px solid rgba(17,19,24,.12)', background: '#fff', cursor: 'pointer', alignSelf: 'flex-end' }}
          >
            Refresh
          </button>
        </div>

        {error ? <p style={{ color: '#c0392b', fontSize: 13 }}>Error: {error}</p> : null}
        {loading ? <p style={{ fontSize: 13, color: '#68707b' }}>Loading…</p> : null}
      </section>

      {/* Audit log table */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Audit log</span>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <small>{audit.length} rows</small>
            <button
              onClick={() => exportCSV(audit, AUDIT_COLS, 'audit-log.csv')}
              style={{ fontSize: 11, padding: '4px 10px', borderRadius: 7, border: '1px solid rgba(17,19,24,.12)', background: '#fff', cursor: 'pointer' }}
            >
              Export CSV
            </button>
          </div>
        </div>
        <div className="admin-table-wrap">
          <table className="admin-table">
            <thead>
              <tr>
                <th>Time</th>
                <th>Type</th>
                <th>Summary</th>
                <th>Status</th>
                <th>Details</th>
              </tr>
            </thead>
            <tbody>
              {audit.length === 0 && !loading ? (
                <tr><td colSpan={5} style={{ color: '#68707b', textAlign: 'center', padding: 20 }}>No audit records</td></tr>
              ) : audit.map(row => (
                <tr key={row.id}>
                  <td><small>{fmtTime(row.at)}</small></td>
                  <td><code style={{ fontSize: 11 }}>{row.type}</code></td>
                  <td>{row.summary}</td>
                  <td>{row.status}</td>
                  <td>
                    {row.meta ? (
                      <details>
                        <summary style={{ cursor: 'pointer', fontSize: 11, color: '#68707b' }}>view</summary>
                        <pre style={{ fontSize: 10.5, marginTop: 6, whiteSpace: 'pre-wrap', wordBreak: 'break-all', maxWidth: 360 }}>
                          {(() => { try { return JSON.stringify(JSON.parse(row.meta), null, 2); } catch { return row.meta; } })()}
                        </pre>
                      </details>
                    ) : null}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {/* External egress table */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>External egress</span>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <small>{egress.length} rows</small>
            <button
              onClick={() => exportCSV(egress, EGRESS_COLS, 'tool-egress.csv')}
              style={{ fontSize: 11, padding: '4px 10px', borderRadius: 7, border: '1px solid rgba(17,19,24,.12)', background: '#fff', cursor: 'pointer' }}
            >
              Export CSV
            </button>
          </div>
        </div>
        <div className="admin-table-wrap">
          <table className="admin-table">
            <thead>
              <tr>
                <th>Time</th>
                <th>Tool</th>
                <th>Agent</th>
                <th>Host</th>
                <th>Method</th>
                <th>Status</th>
                <th>Bytes in</th>
                <th>Bytes out</th>
                <th>ms</th>
              </tr>
            </thead>
            <tbody>
              {egress.length === 0 && !loading ? (
                <tr><td colSpan={9} style={{ color: '#68707b', textAlign: 'center', padding: 20 }}>No egress records</td></tr>
              ) : egress.map(row => (
                <tr key={row.id}>
                  <td><small>{fmtTime(row.at)}</small></td>
                  <td><code style={{ fontSize: 11 }}>{row.tool_name}</code></td>
                  <td><small>{row.agent_id ?? '—'}</small></td>
                  <td><small>{row.host}</small></td>
                  <td><code style={{ fontSize: 11 }}>{row.method}</code></td>
                  <td>
                    <span style={{ color: row.status_code >= 400 ? '#c0392b' : row.status_code >= 200 ? '#27ae60' : '#68707b' }}>
                      {row.status_code ?? '—'}
                    </span>
                  </td>
                  <td><small>{fmtBytes(row.bytes_in)}</small></td>
                  <td><small>{fmtBytes(row.bytes_out)}</small></td>
                  <td><small>{row.duration_ms != null ? `${row.duration_ms}` : '—'}</small></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
