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

export function LogsPage() {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const loadLogs = async () => {
    const res = await window.electronAPI.getConnectionLogs();
    if (res.success) setLogs(res.data);
    setLoading(false);
  };

  useEffect(() => {
    loadLogs();
    const interval = setInterval(loadLogs, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="page">
      <h1>连接日志</h1>

      <div className="card">
        <h3>最近日志 ({logs.length})</h3>
        {loading ? (
          <p>加载中...</p>
        ) : logs.length === 0 ? (
          <p className="empty-text">暂无日志</p>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>时间</th>
                <th>用户ID</th>
                <th>设备ID</th>
                <th>节点ID</th>
                <th>操作</th>
                <th>状态</th>
                <th>消息</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((l) => (
                <tr key={l.id}>
                  <td>{l.created_at}</td>
                  <td>{l.user_id || '-'}</td>
                  <td>{l.device_id || '-'}</td>
                  <td>{l.node_id || '-'}</td>
                  <td>{l.action}</td>
                  <td>
                    <span className={`status-badge ${l.status}`}>
                      {l.status === 'success' ? '✅' : '❌'}
                    </span>
                  </td>
                  <td>{l.message}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
