const { useState: useStateL, useEffect: useEffectL, useMemo: useMemoL } = React;

// ── helpers ───────────────────────────────────────────────────────────────────

function fmtTs(iso) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
  });
}

function fmtRel(iso) {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function statusColor(code) {
  if (!code) return 'var(--ink-3)';
  if (code < 300) return 'var(--pos)';
  if (code < 500) return 'var(--warn)';
  return 'var(--neg)';
}

function actionLabel(type) {
  return (type || '').replace(/_/g, ' ');
}

// ── LogsPage ──────────────────────────────────────────────────────────────────

const LogsPage = () => {
  const I = window.Icons;
  const sb = window.supabaseClient;

  const [adminLogs, setAdminLogs] = useStateL([]);
  const [apiLogs, setApiLogs]     = useStateL([]);
  const [loading, setLoading]     = useStateL(true);
  const [filter, setFilter]       = useStateL('all');
  const [search, setSearch]       = useStateL('');

  const fetchLogs = async () => {
    setLoading(true);
    const [adminRes, apiRes] = await Promise.all([
      sb.from('admin_action_log').select('*').order('created_at', { ascending: false }).limit(100),
      sb.from('api_performance_log').select('*').order('created_at', { ascending: false }).limit(100),
    ]);
    setAdminLogs(adminRes.data || []);
    setApiLogs(apiRes.data || []);
    setLoading(false);
  };

  useEffectL(() => { if (sb) fetchLogs(); }, []);

  // merge + sort
  const allEntries = useMemoL(() => {
    const admin = (adminLogs).map(l => ({
      id: l.id,
      created_at: l.created_at,
      type: 'admin',
      action: l.action_type,
      resource_type: l.resource_type || '',
      resource_id: l.resource_id || '',
      details: l.action_details,
      status_code: null,
      latency: null,
      endpoint: null,
    }));
    const api = (apiLogs).map(l => ({
      id: l.id,
      created_at: l.created_at,
      type: 'api',
      action: `${l.method} ${l.endpoint}`,
      resource_type: l.endpoint || '',
      resource_id: '',
      details: null,
      status_code: l.status_code,
      latency: l.response_time_ms,
      endpoint: l.endpoint,
    }));
    return [...admin, ...api].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  }, [adminLogs, apiLogs]);

  const filtered = useMemoL(() => {
    let list = filter === 'all' ? allEntries : allEntries.filter(e => e.type === filter);
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(e =>
        e.action?.toLowerCase().includes(q) ||
        e.resource_type?.toLowerCase().includes(q) ||
        e.resource_id?.toLowerCase().includes(q)
      );
    }
    return list;
  }, [allEntries, filter, search]);

  const adminCount = adminLogs.length;
  const apiCount   = apiLogs.length;

  // api stats
  const apiStats = useMemoL(() => {
    if (!apiLogs.length) return null;
    const latencies = apiLogs.map(l => l.response_time_ms).filter(v => v != null);
    const errors = apiLogs.filter(l => l.status_code >= 400).length;
    const avgLatency = latencies.length ? Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length) : null;
    const p95 = latencies.length ? latencies.sort((a,b)=>a-b)[Math.floor(latencies.length * 0.95)] : null;
    return { avgLatency, p95, errors, total: apiLogs.length, errorRate: ((errors / apiLogs.length) * 100).toFixed(1) };
  }, [apiLogs]);

  const tabs = [
    { id: 'all',   label: 'All',   count: allEntries.length },
    { id: 'admin', label: 'Admin', count: adminCount },
    { id: 'api',   label: 'API',   count: apiCount },
  ];

  return (
    <div className="page" data-screen-label="Logs">
      <div className="page-h">
        <div>
          <div className="ts">{allEntries.length} entries · last 100 per type</div>
          <h1>Logs</h1>
        </div>
        <div className="acts">
          <button className="btn" onClick={fetchLogs} disabled={loading}>
            <I.refresh size={12} style={loading ? { animation: 'spin 1s linear infinite' } : undefined} />
            Refresh
          </button>
        </div>
      </div>

      {/* API stats strip — only when api tab or all */}
      {apiStats && (filter === 'all' || filter === 'api') && (
        <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 14 }}>
          <div className="kpi">
            <div className="lbl">API requests</div>
            <div className="val">{apiStats.total}</div>
          </div>
          <div className="kpi">
            <div className="lbl">Avg latency</div>
            <div className="val">{apiStats.avgLatency != null ? `${apiStats.avgLatency}ms` : '—'}</div>
          </div>
          <div className="kpi">
            <div className="lbl">p95 latency</div>
            <div className="val">{apiStats.p95 != null ? `${apiStats.p95}ms` : '—'}</div>
          </div>
          <div className="kpi">
            <div className="lbl">Error rate</div>
            <div className="val" style={{ color: apiStats.errors > 0 ? 'var(--neg)' : undefined }}>
              {apiStats.errorRate}%
            </div>
            <div className="sub"><span className="muted">{apiStats.errors} errors</span></div>
          </div>
        </div>
      )}

      <div className="panel" style={{ overflow: 'hidden' }}>
        {/* Toolbar */}
        <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--hairline)', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          {/* Filter tabs */}
          <div className="ftabs" style={{ margin: 0, border: 'none', padding: 0 }}>
            {tabs.map(t => (
              <div
                key={t.id}
                className={'ftab' + (filter === t.id ? ' active' : '')}
                onClick={() => setFilter(t.id)}
              >
                {t.label}
                <span className="ct">{t.count}</span>
              </div>
            ))}
          </div>

          {/* Search */}
          <div style={{ marginLeft: 'auto', position: 'relative' }}>
            <I.search size={12} style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)', pointerEvents: 'none' }} />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Filter…"
              style={{ paddingLeft: 28, paddingRight: 10, height: 28, fontSize: 12.5, width: 180, background: 'var(--surface-2)', border: '1px solid var(--hairline)', borderRadius: 6, color: 'var(--ink)', outline: 'none', boxSizing: 'border-box' }}
            />
          </div>
        </div>

        {/* Table */}
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Loading…</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>No log entries</div>
        ) : (
          <div className="t-wrap">
            <table className="t">
              <thead>
                <tr>
                  <th style={{ width: 160 }}>Time</th>
                  <th style={{ width: 70 }}>Type</th>
                  <th>Action</th>
                  <th>Resource</th>
                  <th style={{ textAlign: 'right', width: 130 }}>Status / ID</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(entry => (
                  <tr key={entry.id}>
                    <td style={{ whiteSpace: 'nowrap' }}>
                      <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-2)' }}>{fmtTs(entry.created_at)}</div>
                      <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 1 }}>{fmtRel(entry.created_at)}</div>
                    </td>
                    <td>
                      <span
                        className="chip"
                        style={entry.type === 'api'
                          ? { background: 'var(--accent-soft, #e8f4ff)', color: 'var(--accent)', border: '1px solid var(--accent-muted, #bfdbfe)' }
                          : undefined
                        }
                      >
                        {entry.type.toUpperCase()}
                      </span>
                    </td>
                    <td>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{actionLabel(entry.action)}</div>
                    </td>
                    <td>
                      {entry.resource_type && (
                        <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{entry.resource_type}</div>
                      )}
                      {entry.resource_id && (
                        <div className="id" style={{ marginTop: 1 }}>{entry.resource_id.slice(0, 8).toUpperCase()}</div>
                      )}
                    </td>
                    <td style={{ textAlign: 'right' }}>
                      {entry.type === 'api' ? (
                        <div>
                          <div style={{ fontSize: 12.5, fontFamily: 'var(--font-mono)', fontWeight: 600, color: statusColor(entry.status_code) }}>
                            {entry.status_code}
                          </div>
                          {entry.latency != null && (
                            <div style={{ fontSize: 11, color: entry.latency > 1000 ? 'var(--warn)' : 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 1 }}>
                              {entry.latency}ms
                            </div>
                          )}
                        </div>
                      ) : (
                        <span className="id">{entry.id.slice(0, 8).toUpperCase()}</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

window.LogsPage = LogsPage;
