/**
 * AdminDashboard Component - Analytics and monitoring dashboard
 */

import { useState, useEffect } from 'react'
import { useAccount, usePublicClient } from 'wagmi'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { MAINNET_TETHER_ABI } from '../../abis/MainnetTether'
import { subscribeToContractEvents } from '../../utils/contractEvents'
import toast from 'react-hot-toast'

export default function AdminDashboard() {
  const { adminActions, auditLogs } = useAdmin()
  const { address } = useAccount()
  const publicClient = usePublicClient()
  const [mainnetTetherPaused, setMainnetTetherPaused] = useState<boolean>(false)

  const stats = {
    totalActions: adminActions.length,
    pending: adminActions.filter((a) => a.status === TransactionRequestStatus.PENDING).length,
    approved: adminActions.filter((a) => a.status === TransactionRequestStatus.APPROVED).length,
    executed: adminActions.filter((a) => a.status === TransactionRequestStatus.SUCCESS).length,
    failed: adminActions.filter((a) => a.status === TransactionRequestStatus.FAILED).length,
    totalAuditLogs: auditLogs.length,
    successRate:
      adminActions.length > 0
        ? (
            (adminActions.filter((a) => a.status === TransactionRequestStatus.SUCCESS).length /
              adminActions.length) *
            100
          ).toFixed(1)
        : '0',
  }

  const recentActions = adminActions.slice(-5).reverse()
  const recentLogs = auditLogs.slice(-5).reverse()

  useEffect(() => {
    if (publicClient && address) {
      // Fetch contract states
      const fetchStates = async () => {
        try {
          // Fetch paused state for MainnetTether
          const paused = await publicClient.readContract({
            address: CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
            abi: MAINNET_TETHER_ABI,
            functionName: 'paused',
          })
          setMainnetTetherPaused(paused as boolean)
        } catch (error) {
          console.error('Error fetching contract states:', error)
        }
      }

      fetchStates()
      const interval = setInterval(fetchStates, 30000) // Refresh every 30 seconds

      // Subscribe to contract events for real-time updates
      let unsubscribePaused: (() => void) | null = null
      let unsubscribeUnpaused: (() => void) | null = null

      subscribeToContractEvents(
        publicClient,
        CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
        MAINNET_TETHER_ABI,
        'Paused',
        (_event) => {
          setMainnetTetherPaused(true)
          toast.success('MainnetTether paused event detected', { icon: '🔔' })
        }
      ).then((unsub) => {
        unsubscribePaused = unsub
      }).catch(() => {})

      subscribeToContractEvents(
        publicClient,
        CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
        MAINNET_TETHER_ABI,
        'Unpaused',
        (_event) => {
          setMainnetTetherPaused(false)
          toast.success('MainnetTether unpaused event detected', { icon: '🔔' })
        }
      ).then((unsub) => {
        unsubscribeUnpaused = unsub
      }).catch(() => {})

      return () => {
        clearInterval(interval)
        if (unsubscribePaused) unsubscribePaused()
        if (unsubscribeUnpaused) unsubscribeUnpaused()
      }
    }
  }, [publicClient, address])

  return (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-black/20 rounded-xl p-4 border border-white/10">
          <div className="text-white/70 text-sm mb-1">Total Actions</div>
          <div className="text-2xl font-bold text-white">{stats.totalActions}</div>
        </div>
        <div className="bg-black/20 rounded-xl p-4 border border-white/10">
          <div className="text-white/70 text-sm mb-1">Pending</div>
          <div className="text-2xl font-bold text-yellow-400">{stats.pending}</div>
        </div>
        <div className="bg-black/20 rounded-xl p-4 border border-white/10">
          <div className="text-white/70 text-sm mb-1">Executed</div>
          <div className="text-2xl font-bold text-green-400">{stats.executed}</div>
        </div>
        <div className="bg-black/20 rounded-xl p-4 border border-white/10">
          <div className="text-white/70 text-sm mb-1">Success Rate</div>
          <div className="text-2xl font-bold text-blue-400">{stats.successRate}%</div>
        </div>
      </div>

      {/* Contract Status */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-black/20 rounded-xl p-4 border border-white/10">
          <div className="flex items-center justify-between mb-2">
            <div className="text-white/70 text-sm">MainnetTether</div>
            <span
              className={`px-3 py-1 rounded text-xs font-semibold ${
                mainnetTetherPaused
                  ? 'bg-red-500/20 text-red-300'
                  : 'bg-green-500/20 text-green-300'
              }`}
            >
              {mainnetTetherPaused ? 'Paused' : 'Active'}
            </span>
          </div>
          <p className="text-white/60 text-xs font-mono">
            {CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER}
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Recent Actions */}
        <div className="bg-black/20 rounded-xl p-6 border border-white/10">
          <h3 className="text-lg font-bold text-white mb-4">Recent Actions</h3>
          {recentActions.length === 0 ? (
            <p className="text-white/60 text-sm">No actions yet</p>
          ) : (
            <div className="space-y-3">
              {recentActions.map((action) => (
                <div
                  key={action.id}
                  className="bg-white/5 rounded-lg p-3 border border-white/10"
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <p className="text-white font-semibold text-sm">{action.type}</p>
                      <p className="text-white/60 text-xs font-mono">
                        {action.contractAddress.slice(0, 20)}...
                      </p>
                    </div>
                    <span
                      className={`px-2 py-1 rounded text-xs ${
                        action.status === TransactionRequestStatus.SUCCESS
                          ? 'bg-green-500/20 text-green-300'
                          : action.status === TransactionRequestStatus.FAILED
                          ? 'bg-red-500/20 text-red-300'
                          : 'bg-yellow-500/20 text-yellow-300'
                      }`}
                    >
                      {action.status}
                    </span>
                  </div>
                  <p className="text-white/50 text-xs mt-2">
                    {new Date(action.createdAt).toLocaleString()}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Recent Audit Logs */}
        <div className="bg-black/20 rounded-xl p-6 border border-white/10">
          <h3 className="text-lg font-bold text-white mb-4">Recent Audit Logs</h3>
          {recentLogs.length === 0 ? (
            <p className="text-white/60 text-sm">No audit logs yet</p>
          ) : (
            <div className="space-y-3">
              {recentLogs.map((log) => (
                <div
                  key={log.id}
                  className="bg-white/5 rounded-lg p-3 border border-white/10"
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <p className="text-white font-semibold text-sm">{log.action}</p>
                      <p className="text-white/60 text-xs font-mono">{log.user.slice(0, 10)}...</p>
                    </div>
                    <span
                      className={`px-2 py-1 rounded text-xs ${
                        log.status === 'success'
                          ? 'bg-green-500/20 text-green-300'
                          : 'bg-red-500/20 text-red-300'
                      }`}
                    >
                      {log.status}
                    </span>
                  </div>
                  <p className="text-white/50 text-xs mt-2">
                    {new Date(log.timestamp).toLocaleString()}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
