import React, { useEffect, useState } from 'react';
import { Table, Spin, Alert } from 'antd';
import {listBtTorrentPeers} from "@/pages/Peer/service";
import {BtTorrentPeer} from "@/pages/Peer/data";


interface PeerTableProps {
  torrentId: number;
}

const PeerTable: React.FC<PeerTableProps> = ({ torrentId }) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [peers, setPeers] = useState<BtTorrentPeer[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPeers = async () => {
      setLoading(true);
      try {
        const data = await listBtTorrentPeers();

        setPeers(data.rows);
      } catch (err) {
        setError('Failed to load peer data.');
      } finally {
        setLoading(false);
      }
    };

    fetchPeers();
  }, [torrentId]);

  const columns = [
    { title: 'Peer Key', dataIndex: 'peerKey', key: 'peerKey' },
    { title: 'IP Address', dataIndex: 'ip', key: 'ip' },
    { title: 'Port', dataIndex: 'port', key: 'port' },
    { title: 'Uploaded', dataIndex: 'uploaded', key: 'uploaded' },
    { title: 'Downloaded', dataIndex: 'downloaded', key: 'downloaded' },
    { title: 'Left', dataIndex: 'left', key: 'left' },
    { title: 'Last Seen', dataIndex: 'lastSeen', key: 'lastSeen' },
  ];

  return (
    <div>
      {error && <Alert message={error} type="error" />}
      {loading ? (
        <Spin size="large" />
      ) : (
        <Table<BtTorrentPeer>
          columns={columns}
          dataSource={peers}
          rowKey="peerKey"
          pagination={false}
        />
      )}
    </div>
  );
};

export default PeerTable;
