// DBIS Participants & Jurisdictions Page
import { useQuery } from '@tanstack/react-query';
import { dbisAdminApi } from '@/services/api/dbisAdminApi';
import DataTable, { Column } from '@/components/shared/DataTable';
import Button from '@/components/shared/Button';
import { AdminPermission } from '@/constants/permissions';
import PermissionGate from '@/components/auth/PermissionGate';
import type { ParticipantInfo } from '@/types';
import { formatDistanceToNow } from 'date-fns';
import StatusIndicator from '@/components/shared/StatusIndicator';

export default function ParticipantsPage() {
  const { data: participants, isLoading } = useQuery({
    queryKey: ['dbis-participants'],
    queryFn: () => dbisAdminApi.getParticipants(),
  });

  const columns: Column<ParticipantInfo>[] = [
    {
      key: 'name',
      header: 'SCB Name',
      sortable: true,
      render: (row) => (
        <a href={`#participant-${row.scbId}`} className="link">
          {row.name}
        </a>
      ),
    },
    {
      key: 'country',
      header: 'Country',
      sortable: true,
    },
    {
      key: 'bic',
      header: 'BIC',
      render: (row) => row.bic || '-',
    },
    {
      key: 'status',
      header: 'Status',
      sortable: true,
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'connectivity',
      header: 'Connectivity',
      render: (row) => <StatusIndicator status={row.connectivity} />,
    },
    {
      key: 'lastHeartbeat',
      header: 'Last Heartbeat',
      render: (row) =>
        row.lastHeartbeat ? formatDistanceToNow(new Date(row.lastHeartbeat), { addSuffix: true }) : '-',
    },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>Participants & Jurisdictions</h1>
        <PermissionGate permission={AdminPermission.SCB_JURISDICTION_SETTINGS}>
          <Button variant="primary">Apply Template Policy</Button>
        </PermissionGate>
      </div>

      <DataTable
        data={participants || []}
        columns={columns}
        loading={isLoading}
        searchable
        pagination={
          participants
            ? {
                page: 1,
                limit: 25,
                total: participants.length,
                onPageChange: () => {},
              }
            : undefined
        }
      />
    </div>
  );
}

