import type { Torrent } from '../shared';
import { Lock } from 'lucide-react';
import { describePeerFlags, formatPercent, formatSpeed } from '../format';

// Connected peers. Not sortable and not virtualised on purpose: the list is capped by the torrent's peer
// limit (50 by default), it churns every poll, and a sort you have to re-establish every five seconds is
// worse than no sort.

type PeersTabProps = { torrent: Torrent };

const HEAD = 'px-3 py-1.5 text-left text-[11px] font-medium uppercase tracking-wide text-muted-foreground';

export const PeersTab = ({ torrent }: PeersTabProps) => {
  const peers = torrent.peers ?? [];

  if (!peers.length) {
    return <p className="p-6 text-center text-sm text-muted-foreground">No peers connected.</p>;
  }

  return (
    <div className="h-full overflow-auto">
      <table className="w-full border-collapse text-xs">
        <thead className="sticky top-0 bg-background/95 backdrop-blur">
          <tr className="border-b border-border">
            <th className={HEAD}>Address</th>
            <th className={HEAD}>Client</th>
            <th className={`${HEAD} text-right`}>Progress</th>
            <th className={`${HEAD} text-right`}>Down</th>
            <th className={`${HEAD} text-right`}>Up</th>
            <th className={HEAD}>Flags</th>
          </tr>
        </thead>
        <tbody>
          {peers.map((peer) => (
            <tr key={`${peer.address}:${peer.port}`} className="border-b border-border/40 hover:bg-muted/40">
              <td className="px-3 py-1.5 font-mono">
                <span className="flex items-center gap-1.5">
                  {peer.isEncrypted && <Lock className="h-3 w-3 shrink-0 text-emerald-500" aria-label="Encrypted" />}
                  {peer.address}:{peer.port}
                </span>
              </td>
              <td className="max-w-[200px] truncate px-3 py-1.5" title={peer.clientName}>
                {peer.clientName || '—'}
              </td>
              <td className="px-3 py-1.5 text-right tabular-nums">{formatPercent(peer.progress)}</td>
              <td className="px-3 py-1.5 text-right tabular-nums text-blue-500">{formatSpeed(peer.rateToClient)}</td>
              <td className="px-3 py-1.5 text-right tabular-nums text-emerald-500">{formatSpeed(peer.rateToPeer)}</td>
              <td className="px-3 py-1.5 font-mono text-muted-foreground" title={describePeerFlags(peer.flagStr)}>
                {peer.flagStr}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};
