/**
 * RealtimeMonitor Component - Real-time contract monitoring with WebSocket support
 */

import { useState, useEffect } from 'react'
import { usePublicClient, useChainId } from 'wagmi'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { getRealtimeMonitor, monitorContractState, type MonitorEvent } from '../../utils/realtimeMonitor'
import toast from 'react-hot-toast'

interface ContractState {
  contractAddress: string
  paused: boolean
  admin: string
  lastUpdate: number
}

export default function RealtimeMonitor() {
  const publicClient = usePublicClient()
  const chainId = useChainId()
  const [monitoring, setMonitoring] = useState(false)
  const [contractStates, setContractStates] = useState<Record<string, ContractState>>({})
  const [events, setEvents] = useState<MonitorEvent[]>([])
  const [wsUrl, setWsUrl] = useState<string>('')

  useEffect(() => {
    if (monitoring && publicClient) {
      const monitor = getRealtimeMonitor(wsUrl || undefined)
      let isMounted = true
      let stopMainnetTether: (() => void) | null = null
      let stopTransactionMirror: (() => void) | null = null

      // Start monitoring MainnetTether
      monitorContractState(
        CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
        publicClient,
        (state) => {
          if (!isMounted) return
          setContractStates((prev) => ({
            ...prev,
            [CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER]: {
              contractAddress: CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
              ...state,
              lastUpdate: Date.now(),
            },
          }))
        }
      ).then((unsubscribe) => {
        stopMainnetTether = unsubscribe
      }).catch(() => {
        stopMainnetTether = null
      })

      // Start monitoring TransactionMirror
      monitorContractState(
        CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR,
        publicClient,
        (state) => {
          if (!isMounted) return
          setContractStates((prev) => ({
            ...prev,
            [CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR]: {
              contractAddress: CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR,
              ...state,
              lastUpdate: Date.now(),
            },
          }))
        }
      ).then((unsubscribe) => {
        stopTransactionMirror = unsubscribe
      }).catch(() => {
        stopTransactionMirror = null
      })

      // Subscribe to events (async handling)
      let unsubscribeBlocks: (() => void) | null = null
      
      monitor.subscribeToBlocks(chainId, (event) => {
        setEvents((prev) => [event, ...prev.slice(0, 49)]) // Keep last 50 events
        if (event.type === 'block') {
          toast(`New block: ${event.data.number}`, { icon: '🔔', duration: 2000 })
        }
      }).then((unsub) => {
        unsubscribeBlocks = unsub
      }).catch(() => {
        // Handle error silently
      })

      // Connect WebSocket if URL provided
      if (wsUrl) {
        monitor.connect(wsUrl)
      }

      return () => {
        isMounted = false
        stopMainnetTether?.()
        stopTransactionMirror?.()
        unsubscribeBlocks?.()
      }
    }
  }, [monitoring, publicClient, chainId, wsUrl])

  const toggleMonitoring = () => {
    setMonitoring((prev) => !prev)
    if (!monitoring) {
      toast.success('Real-time monitoring started')
    } else {
      toast.success('Real-time monitoring stopped')
    }
  }

  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">Real-Time Monitoring</h2>
        <p className="text-white/70 text-sm mb-4">
          Monitor contract state changes and events in real-time using WebSocket or polling fallback.
        </p>

        {/* Controls */}
        <div className="space-y-4 mb-6">
          <div className="flex items-center gap-4">
            <button
              onClick={toggleMonitoring}
              className={`px-6 py-3 rounded-lg font-semibold transition-colors ${
                monitoring
                  ? 'bg-red-600 hover:bg-red-700 text-white'
                  : 'bg-green-600 hover:bg-green-700 text-white'
              }`}
            >
              {monitoring ? '⏸ Stop Monitoring' : '▶ Start Monitoring'}
            </button>
            <div className="flex items-center gap-2">
              <div
                className={`w-3 h-3 rounded-full ${
                  monitoring ? 'bg-green-500 animate-pulse' : 'bg-gray-500'
                }`}
              />
              <span className="text-white/70 text-sm">
                {monitoring ? 'Monitoring Active' : 'Monitoring Inactive'}
              </span>
            </div>
          </div>

          {/* WebSocket URL */}
          <div>
            <label className="block text-white/70 text-sm mb-2">WebSocket URL (Optional)</label>
            <input
              type="text"
              value={wsUrl}
              onChange={(e) => setWsUrl(e.target.value)}
              placeholder="wss://your-monitoring-server.com/ws"
              disabled={monitoring}
              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 disabled:opacity-50"
            />
            <p className="text-white/60 text-xs mt-1">
              Leave empty to use polling fallback (checks every 10 seconds)
            </p>
          </div>
        </div>

        {/* Contract States */}
        {monitoring && (
          <div className="space-y-4">
            <h3 className="text-lg font-bold text-white">Contract States</h3>
            {Object.entries(contractStates).map(([address, state]) => (
              <div
                key={address}
                className="bg-white/5 rounded-lg p-4 border border-white/10"
              >
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="text-white font-semibold">
                      {address === CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER
                        ? 'MainnetTether'
                        : 'TransactionMirror'}
                    </p>
                    <p className="text-white/60 text-xs font-mono">{address.slice(0, 20)}...</p>
                  </div>
                  <span
                    className={`px-3 py-1 rounded text-xs font-semibold ${
                      state.paused
                        ? 'bg-red-500/20 text-red-300'
                        : 'bg-green-500/20 text-green-300'
                    }`}
                  >
                    {state.paused ? 'Paused' : 'Active'}
                  </span>
                </div>
                <div className="grid grid-cols-2 gap-4 mt-3 text-sm">
                  <div>
                    <span className="text-white/70">Admin:</span>
                    <p className="text-white font-mono text-xs">{state.admin}</p>
                  </div>
                  <div>
                    <span className="text-white/70">Last Update:</span>
                    <p className="text-white text-xs">
                      {new Date(state.lastUpdate).toLocaleTimeString()}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Recent Events */}
        {monitoring && events.length > 0 && (
          <div className="mt-6">
            <h3 className="text-lg font-bold text-white mb-4">Recent Events</h3>
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {events.map((event, index) => (
                <div
                  key={index}
                  className="bg-white/5 rounded-lg p-3 border border-white/10"
                >
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-white font-semibold text-sm">{event.type}</span>
                        <span className="text-white/60 text-xs">
                          {new Date(event.timestamp).toLocaleTimeString()}
                        </span>
                      </div>
                      <pre className="text-white/70 text-xs overflow-x-auto">
                        {JSON.stringify(event.data, null, 2)}
                      </pre>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {!monitoring && (
          <div className="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-4">
            <p className="text-yellow-200 text-sm">
              Click &quot;Start Monitoring&quot; to begin real-time monitoring of contract states and events.
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
