"use client";

import type { PendingRequest, TransactionParams } from "@/lib/types";
import RequestCard from "./RequestCard";

interface PendingRequestsProps {
  requests: PendingRequest[];
  onRespond: (id: string, result?: string, error?: { code: number; message: string }) => void;
}

export default function PendingRequests({ requests, onRespond }: PendingRequestsProps) {
  if (requests.length === 0) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <div className="text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-zinc-100 dark:bg-zinc-800">
            <svg
              className="h-8 w-8 text-zinc-400"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth={1.5}
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
              />
            </svg>
          </div>
          <p className="text-sm font-medium text-zinc-600 dark:text-zinc-400">
            Waiting for signing requests...
          </p>
          <p className="mt-1 text-xs text-zinc-400 dark:text-zinc-500">
            Requests sent to the proxy will appear here
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">
          Pending Requests
        </h2>
        <span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-medium text-amber-800 dark:bg-amber-900/30 dark:text-amber-400">
          {requests.length}
        </span>
      </div>
      <div className="space-y-3">
        {[...requests].sort((a, b) => {
          const getNonce = (r: PendingRequest): number | null => {
            const tx = (Array.isArray(r.params) ? r.params[0] : r.params) as TransactionParams;
            return tx?.nonce ? Number(BigInt(tx.nonce)) : null;
          };
          const na = getNonce(a);
          const nb = getNonce(b);
          if (na !== null && nb !== null) return na - nb;
          if (na !== null) return -1;
          if (nb !== null) return 1;
          return a.receivedAt - b.receivedAt;
        }).map((req) => (
          <RequestCard key={req.id} request={req} onRespond={onRespond} />
        ))}
      </div>
    </div>
  );
}
