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

export default function TwoWayBridgeAdmin() {
  const [newAdmin, setNewAdmin] = useState('')
  const [chainSelector, setChainSelector] = useState('')
  const [l2Bridge, setL2Bridge] = useState('')
  const [feeToken, setFeeToken] = useState('')

  const contractAddress = CONTRACT_ADDRESSES.mainnet.TWOWAY_BRIDGE_L1

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

  const { data: canonicalToken } = useReadContract({
    address: contractAddress,
    abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
    functionName: 'canonicalToken',
    chainId: mainnet.id,
    query: {
      enabled: !!contractAddress,
    },
  })

  const { data: feeTokenAddress } = useReadContract({
    address: contractAddress,
    abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
    functionName: 'feeToken',
    chainId: mainnet.id,
    query: {
      enabled: !!contractAddress,
    },
  })

  const { data: destinationChains } = useReadContract({
    address: contractAddress,
    abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
    functionName: 'getDestinationChains',
    chainId: mainnet.id,
    query: {
      enabled: !!contractAddress,
    },
  })

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

  if (!contractAddress) {
    return (
      <div className="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-6">
        <h2 className="text-xl font-bold text-yellow-200 mb-2">
          TwoWayTokenBridge Not Deployed
        </h2>
        <p className="text-yellow-200/80 text-sm">
          The TwoWayTokenBridge contract is not deployed on Mainnet. Deploy the contract first
          before using this admin panel.
        </p>
      </div>
    )
  }

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

    writeContract(
      {
        address: contractAddress,
        abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
        functionName: 'changeAdmin',
        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 handleAddDestination = () => {
    if (!chainSelector || !l2Bridge || !/^0x[a-fA-F0-9]{40}$/.test(l2Bridge)) {
      toast.error('Invalid chain selector or L2 bridge address')
      return
    }

    writeContract(
      {
        address: contractAddress,
        abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
        functionName: 'addDestination',
        args: [BigInt(chainSelector), l2Bridge as `0x${string}`],
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success('Destination added')
          setChainSelector('')
          setL2Bridge('')
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message || 'Transaction failed'}`)
        },
      }
    )
  }

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

    writeContract(
      {
        address: contractAddress,
        abi: TWOWAY_TOKEN_BRIDGE_L1_ABI,
        functionName: 'updateFeeToken',
        args: [feeToken as `0x${string}`],
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success('Fee token updated')
          setFeeToken('')
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message || 'Transaction failed'}`)
        },
      }
    )
  }

  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">Canonical Token:</span>
            <span className="font-mono text-white text-sm">{canonicalToken || 'Loading...'}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Fee Token:</span>
            <span className="font-mono text-white text-sm">
              {feeTokenAddress || 'Loading...'}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-white/70">Destination Chains:</span>
            <span className="font-mono text-white text-sm">
              {destinationChains?.length || 0} configured
            </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">
          {/* 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>

          {/* Add Destination */}
          <div className="space-y-2">
            <label className="block text-white/70 text-sm">Add Destination Chain</label>
            <input
              type="text"
              value={chainSelector}
              onChange={(e) => setChainSelector(e.target.value)}
              placeholder="Chain Selector (e.g., 16015286601757825753)"
              className="w-full 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"
            />
            <input
              type="text"
              value={l2Bridge}
              onChange={(e) => setL2Bridge(e.target.value)}
              placeholder="L2 Bridge Address (0x...)"
              className="w-full 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={handleAddDestination}
              disabled={isPending || isConfirming || !chainSelector || !l2Bridge}
              className="w-full px-6 py-2 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...' : 'Add Destination'}
            </button>
          </div>

          {/* Update Fee Token */}
          <div>
            <label className="block text-white/70 text-sm mb-2">New Fee Token Address</label>
            <div className="flex gap-2">
              <input
                type="text"
                value={feeToken}
                onChange={(e) => setFeeToken(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={handleUpdateFeeToken}
                disabled={isPending || isConfirming || !feeToken}
                className="px-6 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
              >
                {isPending || isConfirming ? 'Processing...' : 'Update Fee Token'}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Destination Chains List */}
      {destinationChains && destinationChains.length > 0 && (
        <div className="bg-black/20 rounded-xl p-6 border border-white/10">
          <h2 className="text-xl font-bold text-white mb-4">Configured Destination Chains</h2>
          <div className="space-y-2">
            {destinationChains.map((chain: bigint, index: number) => (
              <div
                key={index}
                className="flex justify-between items-center p-3 bg-white/5 rounded-lg"
              >
                <span className="font-mono text-white text-sm">Chain: {chain.toString()}</span>
                <span className="text-white/70 text-sm">Chain Selector</span>
              </div>
            ))}
          </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 */}
      {contractAddress && (
        <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>
  )
}
