import { useEffect, useState } from 'react';
import { fetchLogs } from '../api';
import { useWebSocket } from '../hooks/useWebSocket';
import type { AccessLog } from '../types';
import './Logs.css';

const MAX_LOGS = 200;

function statusColor(code: number): string {
  if (code < 300) return 'status--ok';
  if (code < 400) return 'status--redirect';
  if (code < 500) return 'status--client-err';
  return 'status--server-err';
}

export function Logs() {
  const { logs: wsLogs, connected } = useWebSocket();
  const [initLogs, setInitLogs] = useState<AccessLog[]>([]);

  useEffect(() => {
    fetchLogs(1, 50)
      .then(setInitLogs)
      .catch(() => {});
  }, []);

  // Merge: ws logs on top, then initial logs, deduplicated by id
  const seen = new Set<number>();
  const merged: AccessLog[] = [];
  for (const log of [...wsLogs, ...initLogs]) {
    if (!seen.has(log.id)) {
      seen.add(log.id);
      merged.push(log);
    }
    if (merged.length >= MAX_LOGS) break;
  }

  return (
    <div className="logs-page">
      <header className="logs-header">
        <span className="logs-title">LIVE_TELEMETRY</span>
        <span className={`ws-badge ${connected ? 'ws-badge--on' : 'ws-badge--off'}`}>
          <span className="dot dot--sm" /> {connected ? 'STREAMING' : 'RECONNECTING'}
        </span>
      </header>

      <div className="logs-table-wrap">
        <table className="logs-table">
          <thead>
            <tr>
              <th>TIME</th>
              <th>IP</th>
              <th>LOCATION</th>
              <th>METHOD</th>
              <th>PATH</th>
              <th>STATUS</th>
            </tr>
          </thead>
          <tbody>
            {merged.map((log) => (
              <tr key={log.id} className="log-row">
                <td className="td-time">{new Date(log.created_at).toLocaleTimeString()}</td>
                <td className="td-ip">{log.ip}</td>
                <td className="td-loc">{log.city !== 'Unknown' ? `${log.city}, ${log.country}` : log.country}</td>
                <td className={`td-method method--${log.method.toLowerCase()}`}>{log.method}</td>
                <td className="td-path">{log.path}</td>
                <td className={`td-status ${statusColor(log.status_code)}`}>{log.status_code}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {merged.length === 0 && <div className="empty-msg">Waiting for traffic…</div>}
      </div>
    </div>
  );
}
