/**
 * TransactionStatusPoller Component - Real-time transaction status updates
 */

import { useEffect, useState } from 'react'
import { usePublicClient } from 'wagmi'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'

export default function TransactionStatusPoller() {
  const { adminActions, updateAdminAction } = useAdmin()
  const publicClient = usePublicClient()
  const [polling, setPolling] = useState(true)

  useEffect(() => {
    if (!polling || !publicClient) return

    const pendingActions = adminActions.filter(
      (a) =>
        a.hash &&
        (a.status === TransactionRequestStatus.PENDING ||
          a.status === TransactionRequestStatus.EXECUTING)
    )

    if (pendingActions.length === 0) return

    const pollStatus = async () => {
      for (const action of pendingActions) {
        if (!action.hash) continue

        try {
          const receipt = await publicClient.getTransactionReceipt({
            hash: action.hash as `0x${string}`,
          })

          if (receipt) {
            updateAdminAction(action.id, {
              status:
                receipt.status === 'success'
                  ? TransactionRequestStatus.SUCCESS
                  : TransactionRequestStatus.FAILED,
              executedAt: Date.now(),
            })
          }
        } catch (error) {
          // Transaction not yet confirmed, continue polling
        }
      }
    }

    const interval = setInterval(pollStatus, 5000) // Poll every 5 seconds
    return () => clearInterval(interval)
  }, [adminActions, publicClient, polling, updateAdminAction])

  const pendingCount = adminActions.filter(
    (a) =>
      a.hash &&
      (a.status === TransactionRequestStatus.PENDING ||
        a.status === TransactionRequestStatus.EXECUTING)
  ).length

  return (
    <div className="bg-black/20 rounded-xl p-4 border border-white/10">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className={`w-2 h-2 rounded-full ${polling ? 'bg-green-400 animate-pulse' : 'bg-gray-400'}`} />
          <span className="text-white text-sm">
            Status Polling: {polling ? 'Active' : 'Paused'} ({pendingCount} pending)
          </span>
        </div>
        <button
          onClick={() => setPolling(!polling)}
          className={`px-3 py-1 rounded text-sm font-semibold transition-colors ${
            polling
              ? 'bg-yellow-600 hover:bg-yellow-700 text-white'
              : 'bg-green-600 hover:bg-green-700 text-white'
          }`}
        >
          {polling ? 'Pause' : 'Resume'}
        </button>
      </div>
    </div>
  )
}
