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

export default function MainnetTetherAdmin() {
  const [blockNumber, setBlockNumber] = useState('')
  const [newAdmin, setNewAdmin] = useState('')

  const contractAddress = CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER

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

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

  const { data: anchoredBlockCount } = useReadContract({
    address: contractAddress,
    abi: MAINNET_TETHER_ABI,
    functionName: 'getAnchoredBlockCount',
    chainId: mainnet.id,
  })

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

  const handlePause = () => {
    writeContract(
      {
        address: contractAddress,
        abi: MAINNET_TETHER_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: MAINNET_TETHER_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: MAINNET_TETHER_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 handleCheckBlock = () => {
    if (!blockNumber) {
      toast.error('Please enter a block number')
      return
    }
    // This would require a custom hook to read state proofs
    toast('Block checking feature - implement with custom hook', { icon: 'ℹ️' })
  }

  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">Anchored Blocks:</span>
            <span className="font-mono text-white">
              {anchoredBlockCount?.toString() || '0'}
            </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>

      {/* Block 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 State Proof</h2>
        <div className="flex gap-2">
          <input
            type="number"
            value={blockNumber}
            onChange={(e) => setBlockNumber(e.target.value)}
            placeholder="Block number"
            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={handleCheckBlock}
            className="px-6 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-semibold transition-colors"
          >
            Check Block
          </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>
  )
}
