import { useState } from 'react'
import { useChainId } from 'wagmi'
import { useReadContract, useWriteContract, useWaitForTransactionReceipt } from 'wagmi'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { PAYMENT_CHANNEL_MANAGER_ABI } from '../../abis/PaymentChannelManager'
import toast from 'react-hot-toast'
import { chain138, chain2138Testnet } from '../../config/networks'

function getManagerAddress(chainId: number): `0x${string}` | undefined {
  if (chainId === 1) return CONTRACT_ADDRESSES.mainnet.PAYMENT_CHANNEL_MANAGER as `0x${string}` | undefined
  if (chainId === 138) return CONTRACT_ADDRESSES.chain138.PAYMENT_CHANNEL_MANAGER as `0x${string}` | undefined
  if (chainId === 2138) return CONTRACT_ADDRESSES.chain2138.PAYMENT_CHANNEL_MANAGER as `0x${string}` | undefined
  return undefined
}

export default function PaymentChannelAdmin() {
  const chainId = useChainId()
  const managerAddress = getManagerAddress(chainId)
  const [newAdmin, setNewAdmin] = useState('')
  const [newChallengeWindow, setNewChallengeWindow] = useState('')

  const { data: admin } = useReadContract({
    address: managerAddress,
    abi: PAYMENT_CHANNEL_MANAGER_ABI,
    functionName: 'admin',
  })
  const { data: paused } = useReadContract({
    address: managerAddress,
    abi: PAYMENT_CHANNEL_MANAGER_ABI,
    functionName: 'paused',
  })
  const { data: challengeWindowSeconds } = useReadContract({
    address: managerAddress,
    abi: PAYMENT_CHANNEL_MANAGER_ABI,
    functionName: 'challengeWindowSeconds',
  })
  const { data: channelCount } = useReadContract({
    address: managerAddress,
    abi: PAYMENT_CHANNEL_MANAGER_ABI,
    functionName: 'getChannelCount',
  })

  const { writeContract, data: hash, isPending } = useWriteContract()
  const { isLoading: isConfirming } = useWaitForTransactionReceipt({ hash })

  const handlePause = () => {
    if (!managerAddress) return
    writeContract(
      { address: managerAddress, abi: PAYMENT_CHANNEL_MANAGER_ABI, functionName: 'pause' },
      { onSuccess: () => toast.success('Pause submitted'), onError: (e: unknown) => toast.error((e as Error).message) }
    )
  }
  const handleUnpause = () => {
    if (!managerAddress) return
    writeContract(
      { address: managerAddress, abi: PAYMENT_CHANNEL_MANAGER_ABI, functionName: 'unpause' },
      { onSuccess: () => toast.success('Unpause submitted'), onError: (e: unknown) => toast.error((e as Error).message) }
    )
  }
  const handleSetAdmin = () => {
    if (!managerAddress || !newAdmin || !/^0x[a-fA-F0-9]{40}$/.test(newAdmin)) {
      toast.error('Invalid admin address')
      return
    }
    writeContract(
      { address: managerAddress, abi: PAYMENT_CHANNEL_MANAGER_ABI, functionName: 'setAdmin', args: [newAdmin as `0x${string}`] },
      { onSuccess: () => { toast.success('Set admin submitted'); setNewAdmin('') }, onError: (e: unknown) => toast.error((e as Error).message) }
    )
  }
  const handleSetChallengeWindow = () => {
    const sec = newChallengeWindow.trim()
    if (!managerAddress || !sec || isNaN(Number(sec)) || Number(sec) <= 0) {
      toast.error('Enter valid seconds (e.g. 86400 for 24h)')
      return
    }
    writeContract(
      { address: managerAddress, abi: PAYMENT_CHANNEL_MANAGER_ABI, functionName: 'setChallengeWindow', args: [BigInt(sec)] },
      { onSuccess: () => { toast.success('Challenge window update submitted'); setNewChallengeWindow('') }, onError: (e: unknown) => toast.error((e as Error).message) }
    )
  }

  if (managerAddress == null) {
    return (
      <div className="rounded-xl bg-white/5 p-6 text-white/80">
        <p>
          Payment channel manager not deployed on this chain. Set `PAYMENT_CHANNEL_MANAGER`
          in config for Ethereum Mainnet, {chain138.name}, or {chain2138Testnet.name}.
        </p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="rounded-xl bg-white/5 p-6">
        <h2 className="text-xl font-semibold text-white mb-4">Payment Channel Manager (Admin)</h2>
        <dl className="grid gap-2 text-sm">
          <div className="flex gap-2"><dt className="text-white/60">Admin:</dt><dd className="text-white font-mono">{admin ?? '—'}</dd></div>
          <div className="flex gap-2"><dt className="text-white/60">Paused:</dt><dd className="text-white">{paused != null ? String(paused) : '—'}</dd></div>
          <div className="flex gap-2"><dt className="text-white/60">Challenge window:</dt><dd className="text-white">{challengeWindowSeconds != null ? `${Number(challengeWindowSeconds)}s` : '—'}</dd></div>
          <div className="flex gap-2"><dt className="text-white/60">Channels:</dt><dd className="text-white">{channelCount != null ? String(channelCount) : '—'}</dd></div>
        </dl>
      </div>
      <div className="rounded-xl bg-white/5 p-6 grid gap-4 md:grid-cols-2">
        <div>
          <label className="block text-sm text-white/80 mb-1">Pause / Unpause</label>
          <div className="flex gap-2">
            <button onClick={handlePause} disabled={isPending || isConfirming || !!paused} className="rounded-lg bg-amber-600 px-4 py-2 text-white hover:bg-amber-700 disabled:opacity-50">Pause</button>
            <button onClick={handleUnpause} disabled={isPending || isConfirming || !paused} className="rounded-lg bg-emerald-600 px-4 py-2 text-white hover:bg-emerald-700 disabled:opacity-50">Unpause</button>
          </div>
        </div>
        <div>
          <label className="block text-sm text-white/80 mb-1">Set admin</label>
          <input type="text" placeholder="0x..." value={newAdmin} onChange={(e) => setNewAdmin(e.target.value)} className="w-full rounded-lg bg-black/30 border border-white/20 px-4 py-2 text-white placeholder-white/40 mb-2" />
          <button onClick={handleSetAdmin} disabled={isPending || isConfirming} className="rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50">Set admin</button>
        </div>
        <div>
          <label className="block text-sm text-white/80 mb-1">Challenge window (seconds, e.g. 86400 = 24h)</label>
          <input type="text" placeholder="86400" value={newChallengeWindow} onChange={(e) => setNewChallengeWindow(e.target.value)} className="w-full rounded-lg bg-black/30 border border-white/20 px-4 py-2 text-white placeholder-white/40 mb-2" />
          <button onClick={handleSetChallengeWindow} disabled={isPending || isConfirming} className="rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50">Set window</button>
        </div>
      </div>
    </div>
  )
}
