import { useState } from 'react'
import { useReadContract, useWriteContract, useWaitForTransactionReceipt, usePublicClient } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { TRANSACTION_MIRROR_ABI } from '../../abis/TransactionMirror'
import toast from 'react-hot-toast'

export default function TransactionMirrorAdmin() {
  const publicClient = usePublicClient({ chainId: mainnet.id })
  const [newAdmin, setNewAdmin] = useState('')
  const [txHash, setTxHash] = useState('')

  const contractAddress = CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR

  // Read contract state
  const { data: admin, refetch: refetchAdmin } = useReadContract({
    address: contractAddress,
    abi: TRANSACTION_MIRROR_ABI,
    functionName: 'admin',
    chainId: mainnet.id,
  })

  const { data: paused, refetch: refetchPaused } = useReadContract({
    address: contractAddress,
    abi: TRANSACTION_MIRROR_ABI,
    functionName: 'paused',
    chainId: mainnet.id,
  })

  const { data: mirroredCount } = useReadContract({
    address: contractAddress,
    abi: TRANSACTION_MIRROR_ABI,
    functionName: 'getMirroredTransactionCount',
    chainId: mainnet.id,
  })

  const { data: maxBatchSize } = useReadContract({
    address: contractAddress,
    abi: TRANSACTION_MIRROR_ABI,
    functionName: 'MAX_BATCH_SIZE',
    chainId: mainnet.id,
  })

  // Write contract functions
  const { writeContract, data: hash, isPending } = useWriteContract()
  const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({
    hash,
  })

  const handlePause = () => {
    writeContract(
      {
        address: contractAddress,
        abi: TRANSACTION_MIRROR_ABI,
        functionName: 'pause',
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success('Pause transaction submitted')
          refetchPaused()
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message || 'Transaction failed'}`)
        },
      }
    )
  }

  const handleUnpause = () => {
    writeContract(
      {
        address: contractAddress,
        abi: TRANSACTION_MIRROR_ABI,
        functionName: 'unpause',
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success('Unpause transaction submitted')
          refetchPaused()
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message || 'Transaction failed'}`)
        },
      }
    )
  }

  const handleSetAdmin = () => {
    if (!newAdmin || !/^0x[a-fA-F0-9]{40}$/.test(newAdmin)) {
      toast.error('Invalid admin address')
      return
    }

    writeContract(
      {
        address: contractAddress,
        abi: TRANSACTION_MIRROR_ABI,
        functionName: 'setAdmin',
        args: [newAdmin as `0x${string}`],
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success('Admin change transaction submitted')
          setNewAdmin('')
          refetchAdmin()
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message || 'Transaction failed'}`)
        },
      }
    )
  }

  const handleCheckTransaction = async () => {
    if (!txHash || !/^0x[a-fA-F0-9]{64}$/.test(txHash)) {
      toast.error('Invalid transaction hash')
      return
    }

    if (!publicClient) {
      toast.error('Public client not available')
      return
    }

    try {
      const receipt = await publicClient.getTransactionReceipt({ hash: txHash as `0x${string}` })
      
      if (receipt) {
        toast.success(
          `Transaction found: ${receipt.status === 'success' ? 'Success' : 'Failed'} (Block: ${receipt.blockNumber})`,
          { duration: 5000 }
        )
        
        // Try to check if transaction is mirrored
        try {
          // Convert hex string to bytes32 (ensure it's 66 chars: 0x + 64 hex digits)
          const txHashBytes32 = txHash.length === 66 ? txHash as `0x${string}` : `0x${txHash.slice(2).padStart(64, '0')}` as `0x${string}`
          const isMirrored = await publicClient.readContract({
            address: contractAddress,
            abi: TRANSACTION_MIRROR_ABI,
            functionName: 'isMirrored',
            args: [txHashBytes32],
          })
          if (isMirrored) {
            toast('Transaction is mirrored on mainnet', { icon: '✓' })
          } else {
            toast('Transaction is not mirrored yet', { icon: 'ℹ️' })
          }
        } catch (error: any) {
          // Contract function may not exist or transaction not mirrored yet
          console.error('Error checking mirror status:', error)
        }
      }
    } catch (error: any) {
      if (error.message?.includes('Transaction receipt not found')) {
        toast.error('Transaction not found or not yet mined')
      } else {
        toast.error(`Error checking transaction: ${error.message}`)
      }
    }
  }

  return (
    <div className="space-y-6">
      {/* Contract Info */}
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Contract Information</h2>
        <div className="space-y-3">
          <div className="flex justify-between">
            <span className="text-white/70">Contract Address:</span>
            <span className="font-mono text-white text-sm">{contractAddress}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Current Admin:</span>
            <span className="font-mono text-white text-sm">{admin || 'Loading...'}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Status:</span>
            <span
              className={`font-semibold ${paused ? 'text-red-400' : 'text-green-400'}`}
            >
              {paused ? '⏸️ Paused' : '▶️ Active'}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Mirrored Transactions:</span>
            <span className="font-mono text-white">
              {mirroredCount?.toString() || '0'}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Max Batch Size:</span>
            <span className="font-mono text-white">
              {maxBatchSize?.toString() || '100'}
            </span>
          </div>
        </div>
      </div>

      {/* Admin Actions */}
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Admin Actions</h2>
        <div className="space-y-4">
          {/* Pause/Unpause */}
          <div className="flex gap-4">
            <button
              onClick={handlePause}
              disabled={isPending || isConfirming || paused}
              className="flex-1 px-6 py-3 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
            >
              {isPending || isConfirming ? 'Processing...' : 'Pause Contract'}
            </button>
            <button
              onClick={handleUnpause}
              disabled={isPending || isConfirming || !paused}
              className="flex-1 px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
            >
              {isPending || isConfirming ? 'Processing...' : 'Unpause Contract'}
            </button>
          </div>

          {/* Set Admin */}
          <div>
            <label className="block text-white/70 text-sm mb-2">New Admin Address</label>
            <div className="flex gap-2">
              <input
                type="text"
                value={newAdmin}
                onChange={(e) => setNewAdmin(e.target.value)}
                placeholder="0x..."
                className="flex-1 px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
              />
              <button
                onClick={handleSetAdmin}
                disabled={isPending || isConfirming || !newAdmin}
                className="px-6 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"
              >
                {isPending || isConfirming ? 'Processing...' : 'Set Admin'}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Transaction Query */}
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Query Mirrored Transaction</h2>
        <div className="flex gap-2">
          <input
            type="text"
            value={txHash}
            onChange={(e) => setTxHash(e.target.value)}
            placeholder="Transaction hash (0x...)"
            className="flex-1 px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500 font-mono text-sm"
          />
          <button
            onClick={handleCheckTransaction}
            className="px-6 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-semibold transition-colors"
          >
            Check Transaction
          </button>
        </div>
      </div>

      {/* Transaction Status */}
      {hash && (
        <div className="bg-blue-500/20 border border-blue-500/50 rounded-lg p-4">
          <p className="text-blue-200 text-sm">
            Transaction: <span className="font-mono">{hash}</span>
          </p>
          {isConfirming && <p className="text-blue-200 text-sm mt-2">⏳ Confirming...</p>}
          {isSuccess && (
            <p className="text-green-200 text-sm mt-2">
              ✅ Transaction confirmed!{' '}
              <a
                href={`https://etherscan.io/tx/${hash}`}
                target="_blank"
                rel="noopener noreferrer"
                className="underline"
              >
                View on Etherscan
              </a>
            </p>
          )}
        </div>
      )}

      {/* Explorer Link */}
      <div className="text-center">
        <a
          href={`https://etherscan.io/address/${contractAddress}`}
          target="_blank"
          rel="noopener noreferrer"
          className="text-blue-400 hover:text-blue-300 underline text-sm"
        >
          View Contract on Etherscan →
        </a>
      </div>
    </div>
  )
}
