/**
 * EmergencyControls Component - Emergency procedures and circuit breakers
 */

import { useState } from 'react'
import { useWriteContract } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { MAINNET_TETHER_ABI } from '../../abis/MainnetTether'
import { TRANSACTION_MIRROR_ABI } from '../../abis/TransactionMirror'
import { useAdmin } from '../../contexts/AdminContext'
import toast from 'react-hot-toast'

export default function EmergencyControls() {
  const { addAuditLog } = useAdmin()
  const [confirmText, setConfirmText] = useState('')
  const { writeContract, isPending } = useWriteContract()

  const contracts = [
    { name: 'MainnetTether', address: CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER, abi: MAINNET_TETHER_ABI },
    { name: 'TransactionMirror', address: CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR, abi: TRANSACTION_MIRROR_ABI },
  ]

  const handleEmergencyPause = (contractAddress: string, contractName: string) => {
    if (confirmText !== 'EMERGENCY') {
      toast.error('Please type "EMERGENCY" to confirm')
      return
    }

    writeContract(
      {
        address: contractAddress as `0x${string}`,
        abi: MAINNET_TETHER_ABI,
        functionName: 'pause',
        chainId: mainnet.id,
      },
      {
        onSuccess: () => {
          toast.success(`${contractName} paused`)
          addAuditLog({
            user: 'admin',
            action: 'emergency_pause',
            resourceType: 'contract',
            resourceId: contractAddress,
            details: { contractName },
            status: 'success',
          })
          setConfirmText('')
        },
        onError: (error: any) => {
          toast.error(`Error: ${error.message}`)
        },
      }
    )
  }

  const handleEmergencyPauseAll = () => {
    if (confirmText !== 'EMERGENCY') {
      toast.error('Please type "EMERGENCY" to confirm')
      return
    }

    toast('Pausing all contracts...', { icon: '⏳' })
    contracts.forEach((contract) => {
      handleEmergencyPause(contract.address, contract.name)
    })
  }

  return (
    <div className="bg-red-500/10 border-2 border-red-500/50 rounded-xl p-6">
      <h2 className="text-xl font-bold text-red-300 mb-4">⚠️ Emergency Controls</h2>
      <p className="text-red-200/80 text-sm mb-6">
        Use these controls only in emergency situations. All actions are logged and irreversible.
      </p>

      <div className="space-y-4">
        <div>
          <label className="block text-red-200 text-sm mb-2">
            Type "EMERGENCY" to enable emergency controls:
          </label>
          <input
            type="text"
            value={confirmText}
            onChange={(e) => setConfirmText(e.target.value)}
            placeholder="EMERGENCY"
            className="w-full px-4 py-2 bg-white/10 border border-red-500/50 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-red-500"
          />
        </div>

        <div className="space-y-3">
          {contracts.map((contract) => (
            <div
              key={contract.address}
              className="bg-black/20 rounded-lg p-4 border border-red-500/30"
            >
              <div className="flex justify-between items-center">
                <div>
                  <p className="text-white font-semibold">{contract.name}</p>
                  <p className="text-white/60 text-xs font-mono">{contract.address.slice(0, 20)}...</p>
                </div>
                <button
                  onClick={() => handleEmergencyPause(contract.address, contract.name)}
                  disabled={isPending || confirmText !== 'EMERGENCY'}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
                >
                  Pause
                </button>
              </div>
            </div>
          ))}

          <div className="bg-red-600/20 border-2 border-red-600 rounded-lg p-4">
            <div className="flex justify-between items-center">
              <div>
                <p className="text-red-200 font-bold">Pause All Contracts</p>
                <p className="text-red-200/70 text-xs">This will pause all admin contracts simultaneously</p>
              </div>
              <button
                onClick={handleEmergencyPauseAll}
                disabled={isPending || confirmText !== 'EMERGENCY'}
                className="px-6 py-3 bg-red-700 hover:bg-red-800 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-bold transition-colors"
              >
                PAUSE ALL
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
