/**
 * TransactionRetry Component - Retry failed transactions
 */

import { useState, useEffect } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { TransactionRequestStatus } from '../../types/admin'
import { MAINNET_TETHER_ABI } from '../../abis/MainnetTether'
import { TRANSACTION_MIRROR_ABI } from '../../abis/TransactionMirror'
import toast from 'react-hot-toast'

export default function TransactionRetry() {
  const { adminActions, updateAdminAction } = useAdmin()
  const [retryingId, setRetryingId] = useState<string | null>(null)
  const { writeContract, data: hash, isPending } = useWriteContract()
  const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({ hash })

  const failedActions = adminActions.filter(
    (a) => a.status === TransactionRequestStatus.FAILED
  )

  const getABI = (contractAddress: string) => {
    if (contractAddress === '0x15DF1D5BFDD8Aa4b380445D4e3E9B38d34283619') {
      return MAINNET_TETHER_ABI
    }
    return TRANSACTION_MIRROR_ABI
  }

  const handleRetry = (action: any) => {
    setRetryingId(action.id)

    const abi = getABI(action.contractAddress)

    writeContract(
      {
        address: action.contractAddress as `0x${string}`,
        abi,
        functionName: action.functionName as any,
        args: action.args || [],
        chainId: mainnet.id,
      },
      {
        onSuccess: (txHash) => {
          updateAdminAction(action.id, {
            status: TransactionRequestStatus.EXECUTING,
            hash: txHash,
          })
          toast.success('Transaction retried')
        },
        onError: (error: any) => {
          updateAdminAction(action.id, {
            status: TransactionRequestStatus.FAILED,
            error: error.message,
          })
          toast.error(`Retry failed: ${error.message}`)
          setRetryingId(null)
        },
      }
    )
  }

  useEffect(() => {
    if (isSuccess && hash && retryingId) {
      const action = adminActions.find((a) => a.id === retryingId)
      if (action) {
        updateAdminAction(retryingId, {
          status: TransactionRequestStatus.SUCCESS,
          hash,
          executedAt: Date.now(),
        })
        toast.success('Transaction retry successful!')
        setRetryingId(null)
      }
    }
  }, [isSuccess, hash, retryingId, adminActions, updateAdminAction])

  if (failedActions.length === 0) {
    return (
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Transaction Retry</h2>
        <p className="text-white/60">No failed transactions to retry</p>
      </div>
    )
  }

  return (
    <div className="bg-black/20 rounded-xl p-6 border border-white/10">
      <h2 className="text-xl font-bold text-white mb-4">Transaction Retry</h2>
      <p className="text-white/70 text-sm mb-4">
        Retry failed transactions with the same or updated parameters.
      </p>

      <div className="space-y-3">
        {failedActions.map((action) => (
          <div
            key={action.id}
            className="bg-red-500/10 border border-red-500/30 rounded-lg p-4"
          >
            <div className="flex justify-between items-start">
              <div className="flex-1">
                <p className="text-white font-semibold">{action.functionName}</p>
                <p className="text-white/60 text-xs font-mono mt-1">
                  {action.contractAddress.slice(0, 20)}...
                </p>
                {action.error && (
                  <p className="text-red-400 text-xs mt-2">Error: {action.error}</p>
                )}
                <p className="text-white/50 text-xs mt-2">
                  Failed: {new Date(action.createdAt).toLocaleString()}
                </p>
              </div>
              <button
                onClick={() => handleRetry(action)}
                disabled={isPending || retryingId === action.id}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
              >
                {retryingId === action.id ? (isConfirming ? 'Confirming...' : 'Retrying...') : 'Retry'}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
