/**
 * TransactionPreview Component - Preview and simulate transactions
 */

import { useState } from 'react'
import { usePublicClient } from 'wagmi'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { MAINNET_TETHER_ABI } from '../../abis/MainnetTether'
import { TRANSACTION_MIRROR_ABI } from '../../abis/TransactionMirror'
import { simulateFunctionCall, getSimulationStatusEmoji } from '../../utils/transactionSimulator'
import toast from 'react-hot-toast'

export default function TransactionPreview() {
  const publicClient = usePublicClient()
  const [contractAddress, setContractAddress] = useState(CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER)
  const [functionName, setFunctionName] = useState('pause')
  const [args, setArgs] = useState('[]')
  const [preview, setPreview] = useState<any>(null)
  const [isSimulating, setIsSimulating] = useState(false)

  const getABI = () => {
    return contractAddress === CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER
      ? MAINNET_TETHER_ABI
      : TRANSACTION_MIRROR_ABI
  }

  const handlePreview = async () => {
    if (!publicClient) {
      toast.error('Provider not available')
      return
    }

    setIsSimulating(true)
    try {
      const parsedArgs = JSON.parse(args || '[]')
      const abi = getABI()

      // Get function from ABI
      const func = abi.find((item: any) => item.name === functionName && item.type === 'function')
      if (!func) {
        toast.error('Function not found in ABI')
        setIsSimulating(false)
        return
      }

      // Simulate transaction
      const simulation = await simulateFunctionCall(
        publicClient,
        contractAddress as `0x${string}`,
        abi,
        functionName,
        parsedArgs
      )

      setPreview({
        contractAddress,
        functionName,
        args: parsedArgs,
        gasEstimate: simulation.gasEstimate.toString(),
        returnValue: simulation.returnValue,
        success: simulation.success,
        error: simulation.error,
        abi: func,
        timestamp: Date.now(),
      })

      if (simulation.success) {
        toast.success('Transaction simulation successful', { icon: '✅' })
      } else {
        toast.error(`Simulation failed: ${simulation.error}`, { icon: '❌' })
      }
    } catch (error: any) {
      toast.error(`Preview failed: ${error.message}`)
    }
    setIsSimulating(false)
  }

  return (
    <div className="space-y-6">
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Transaction Preview</h2>
        <p className="text-white/70 text-sm mb-4">
          Preview and simulate transactions before execution.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Contract Address</label>
            <select
              value={contractAddress}
              onChange={(e) => setContractAddress(e.target.value as `0x${string}`)}
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-blue-500"
            >
              <option value={CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER}>MainnetTether</option>
              <option value={CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR}>TransactionMirror</option>
            </select>
          </div>

          <div>
            <label className="block text-white/70 text-sm mb-2">Function Name</label>
            <input
              type="text"
              value={functionName}
              onChange={(e) => setFunctionName(e.target.value)}
              placeholder="pause"
              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"
            />
          </div>

          <div>
            <label className="block text-white/70 text-sm mb-2">Arguments (JSON array)</label>
            <input
              type="text"
              value={args}
              onChange={(e) => setArgs(e.target.value)}
              placeholder='[] or ["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 font-mono text-sm"
            />
          </div>

          <button
            onClick={handlePreview}
            disabled={isSimulating}
            className="w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
          >
            {isSimulating ? 'Simulating...' : 'Preview Transaction'}
          </button>
        </div>
      </div>

      {preview && (
        <div className="bg-black/20 rounded-xl p-6 border border-white/10">
          <h3 className="text-lg font-bold text-white mb-4">Preview Results</h3>
          <div className="space-y-3">
            <div className="bg-white/5 rounded-lg p-4">
              <p className="text-white/70 text-sm mb-1">Contract</p>
              <p className="text-white font-mono text-sm">{preview.contractAddress}</p>
            </div>
            <div className="bg-white/5 rounded-lg p-4">
              <p className="text-white/70 text-sm mb-1">Function</p>
              <p className="text-white font-semibold">{preview.functionName}</p>
            </div>
            <div className="bg-white/5 rounded-lg p-4">
              <p className="text-white/70 text-sm mb-1">Arguments</p>
              <pre className="text-white text-xs font-mono overflow-x-auto">
                {JSON.stringify(preview.args, null, 2)}
              </pre>
            </div>
            <div className="bg-white/5 rounded-lg p-4">
              <p className="text-white/70 text-sm mb-1">Estimated Gas</p>
              <p className="text-white font-mono">{preview.gasEstimate}</p>
            </div>
            {preview.success !== undefined && (
              <div className={`rounded-lg p-4 ${
                preview.success ? 'bg-green-500/20 border border-green-500/50' : 'bg-red-500/20 border border-red-500/50'
              }`}>
                <p className="text-white/70 text-sm mb-1">
                  Simulation Status {getSimulationStatusEmoji({ success: preview.success, gasEstimate: BigInt(preview.gasEstimate || '0'), error: preview.error })}
                </p>
                <p className={preview.success ? 'text-green-300' : 'text-red-300'}>
                  {preview.success ? 'Success' : preview.error || 'Failed'}
                </p>
              </div>
            )}
            {preview.returnValue !== undefined && preview.returnValue !== null && (
              <div className="bg-white/5 rounded-lg p-4">
                <p className="text-white/70 text-sm mb-1">Return Value</p>
                <pre className="text-white text-xs font-mono overflow-x-auto">
                  {JSON.stringify(preview.returnValue, null, 2)}
                </pre>
              </div>
            )}
            {preview.abi && (
              <div className="bg-white/5 rounded-lg p-4">
                <p className="text-white/70 text-sm mb-1">Function Signature</p>
                <p className="text-white text-xs font-mono">
                  {preview.abi.name}({preview.abi.inputs?.map((i: any) => i.type).join(', ') || ''})
                </p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
