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

export function NodesPage() {
  const [nodes, setNodes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const loadNodes = async () => {
    const res = await window.electronAPI.listNodes();
    if (res.success) setNodes(res.data);
    setLoading(false);
  };

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

  return (
    <div className="page">
      <h1>转发节点状态</h1>

      <div className="card">
        <h3>节点列表 ({nodes.length})</h3>
        {loading ? (
          <p>加载中...</p>
        ) : nodes.length === 0 ? (
          <p className="empty-text">暂无注册节点，请启动 Relay Node 程序</p>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>名称</th>
                <th>地址</th>
                <th>状态</th>
                <th>负载</th>
                <th>最后心跳</th>
              </tr>
            </thead>
            <tbody>
              {nodes.map((n) => (
                <tr key={n.id}>
                  <td>{n.id}</td>
                  <td>{n.name}</td>
                  <td>{n.host}:{n.port}</td>
                  <td>
                    <span className={`status-badge ${n.status}`}>
                      {n.status === 'online' ? '🟢 在线' : n.status === 'busy' ? '🟡 繁忙' : '⚫ 离线'}
                    </span>
                  </td>
                  <td>
                    <div className="load-bar">
                      <div className="load-fill" style={{ width: `${Math.min(n.load, 100)}%` }} />
                      <span>{n.load}%</span>
                    </div>
                  </td>
                  <td>{n.last_heartbeat_at}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
