import { useState } from 'react'
import { useAccount, useChainId } from 'wagmi'
import MainnetTetherAdmin from '../components/admin/MainnetTetherAdmin'
import TransactionMirrorAdmin from '../components/admin/TransactionMirrorAdmin'
import TwoWayBridgeAdmin from '../components/admin/TwoWayBridgeAdmin'
import ImpersonationMode from '../components/admin/ImpersonationMode'
import MultiSigAdmin from '../components/admin/MultiSigAdmin'
import TransactionQueue from '../components/admin/TransactionQueue'
import AdminDashboard from '../components/admin/AdminDashboard'
import EmergencyControls from '../components/admin/EmergencyControls'
import AuditLogViewer from '../components/admin/AuditLogViewer'
import GasOptimizer from '../components/admin/GasOptimizer'
import BatchOperations from '../components/admin/BatchOperations'
import TransactionTemplates from '../components/admin/TransactionTemplates'
import SessionManager from '../components/admin/SessionManager'
import TransactionRetry from '../components/admin/TransactionRetry'
import OffChainServices from '../components/admin/OffChainServices'
import TransactionPreview from '../components/admin/TransactionPreview'
import TransactionStatusPoller from '../components/admin/TransactionStatusPoller'
import RoleBasedAccess from '../components/admin/RoleBasedAccess'
import TimeLockedActions from '../components/admin/TimeLockedActions'
import WalletDeployment from '../components/admin/WalletDeployment'
import MultiChainAdmin from '../components/admin/MultiChainAdmin'
import ScheduledActions from '../components/admin/ScheduledActions'
import WalletBalance from '../components/admin/WalletBalance'
import OwnerManagement from '../components/admin/OwnerManagement'
import WalletBackup from '../components/admin/WalletBackup'
import TransactionQueuePriority from '../components/admin/TransactionQueuePriority'
import HardwareWalletSupport from '../components/admin/HardwareWalletSupport'
import FunctionPermissions from '../components/admin/FunctionPermissions'
import RealtimeMonitor from '../components/admin/RealtimeMonitor'
import PaymentChannels from '../components/admin/PaymentChannels'
import PaymentChannelAdmin from '../components/admin/PaymentChannelAdmin'
import StateChannels from '../components/admin/StateChannels'
import { chain138 } from '../config/networks'

type TabType = 'dashboard' | 'mainnet-tether' | 'transaction-mirror' | 'two-way-bridge' | 'channels' | 'state-channels' | 'channel-admin' | 'multisig' | 'queue' | 'impersonation' | 'emergency' | 'audit' | 'gas' | 'batch' | 'templates' | 'retry' | 'services' | 'preview' | 'roles' | 'timelock' | 'wallet' | 'multichain' | 'schedule' | 'balance' | 'owners' | 'backup' | 'priority' | 'hardware' | 'permissions' | 'realtime'

export default function AdminPanel() {
  const { address, isConnected } = useAccount()
  const chainId = useChainId()
  const [activeTab, setActiveTab] = useState<TabType>('dashboard')

  const isSupportedChain = chainId === 1 || chainId === chain138.id

  const tabs = [
    { id: 'dashboard' as TabType, label: 'Dashboard', icon: '📊' },
    { id: 'mainnet-tether' as TabType, label: 'Mainnet Tether', icon: '🔗' },
    { id: 'transaction-mirror' as TabType, label: 'Transaction Mirror', icon: '📋' },
    { id: 'two-way-bridge' as TabType, label: 'Two-Way Bridge', icon: '🌉' },
    { id: 'channels' as TabType, label: 'Channels', icon: '💸' },
    { id: 'state-channels' as TabType, label: 'State Channels', icon: '📜' },
    { id: 'channel-admin' as TabType, label: 'Channel Admin', icon: '⚙️' },
    { id: 'multisig' as TabType, label: 'Multi-Sig', icon: '👥' },
    { id: 'queue' as TabType, label: 'Queue', icon: '📝' },
    { id: 'impersonation' as TabType, label: 'Impersonation', icon: '🎭' },
    { id: 'gas' as TabType, label: 'Gas Optimizer', icon: '⛽' },
    { id: 'batch' as TabType, label: 'Batch Ops', icon: '📦' },
    { id: 'templates' as TabType, label: 'Templates', icon: '📋' },
    { id: 'preview' as TabType, label: 'Preview', icon: '👁️' },
    { id: 'retry' as TabType, label: 'Retry', icon: '🔄' },
    { id: 'services' as TabType, label: 'Services', icon: '🔧' },
    { id: 'roles' as TabType, label: 'Roles', icon: '👤' },
    { id: 'timelock' as TabType, label: 'Time Lock', icon: '⏰' },
    { id: 'wallet' as TabType, label: 'Deploy Wallet', icon: '💼' },
    { id: 'owners' as TabType, label: 'Owners', icon: '👥' },
    { id: 'balance' as TabType, label: 'Balances', icon: '💰' },
    { id: 'backup' as TabType, label: 'Backup', icon: '💾' },
    { id: 'priority' as TabType, label: 'Priority Queue', icon: '⚡' },
    { id: 'multichain' as TabType, label: 'Multi-Chain', icon: '🌐' },
    { id: 'schedule' as TabType, label: 'Schedule', icon: '⏲️' },
    { id: 'audit' as TabType, label: 'Audit Logs', icon: '📜' },
    { id: 'emergency' as TabType, label: 'Emergency', icon: '🚨' },
    { id: 'hardware' as TabType, label: 'Hardware', icon: '🔷' },
    { id: 'permissions' as TabType, label: 'Permissions', icon: '🔐' },
    { id: 'realtime' as TabType, label: 'Real-Time', icon: '📡' },
  ]

  if (!isConnected) {
    return (
      <div className="container mx-auto px-4 py-12 max-w-7xl">
        <div className="bg-white/10 backdrop-blur-xl rounded-2xl shadow-2xl border border-white/20 p-8 text-center">
          <h1 className="text-3xl font-bold text-white mb-4">Admin Panel</h1>
          <p className="text-white/80 mb-6">Please connect your wallet to access the admin panel.</p>
          <div className="inline-block bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-4">
            <p className="text-yellow-200 text-sm">
              ⚠️ Admin functions require wallet connection and admin privileges
            </p>
          </div>
        </div>
      </div>
    )
  }

  if (!isSupportedChain) {
    return (
      <div className="container mx-auto px-4 py-12 max-w-7xl">
        <div className="bg-white/10 backdrop-blur-xl rounded-2xl shadow-2xl border border-white/20 p-8 text-center">
          <h1 className="text-3xl font-bold text-white mb-4">Admin Panel</h1>
          <p className="text-white/80 mb-6">
            Please switch to Ethereum Mainnet (1) or {chain138.name} to access admin functions.
          </p>
          <div className="inline-block bg-red-500/20 border border-red-500/50 rounded-lg p-4">
            <p className="text-red-200 text-sm">
              Current network: Chain ID {chainId}. Use Mainnet (1) or {chain138.name}.
            </p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-7xl">
      <div className="bg-white/10 backdrop-blur-xl rounded-2xl shadow-2xl border border-white/20 overflow-hidden">
        {/* Header */}
        <div className="border-b border-white/20 p-6 bg-gradient-to-r from-blue-600/20 via-purple-600/20 to-pink-600/20 text-center">
          <h1 className="text-3xl font-bold text-white mb-2">Admin Panel</h1>
          <p className="text-white/70 text-sm">
            Connected as: <span className="font-mono text-white/90">{address}</span>
          </p>
        </div>

        {/* Tabs — mobile select + desktop scroll */}
        <div className="sm:hidden p-3 border-b border-white/20 bg-black/30">
          <label htmlFor="admin-tab-select" className="block text-xs text-white/60 mb-1">Section</label>
          <select
            id="admin-tab-select"
            value={activeTab}
            onChange={(e) => setActiveTab(e.target.value as TabType)}
            className="w-full bg-[#1a1d24] text-white border border-white/20 rounded-lg px-3 py-3 text-sm min-h-[44px]"
          >
            {tabs.map((tab) => (
              <option key={tab.id} value={tab.id}>
                {tab.icon} {tab.label}
              </option>
            ))}
          </select>
        </div>
        <div className="admin-tabs hidden sm:flex border-b border-white/20 bg-black/20 overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`shrink-0 px-4 sm:px-6 py-3 sm:py-4 font-semibold transition-all duration-300 whitespace-nowrap min-h-[44px] ${
                activeTab === tab.id
                  ? 'bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 text-white border-b-2 border-white'
                  : 'text-white/70 hover:text-white hover:bg-white/10'
              }`}
            >
              <span className="mr-1 sm:mr-2">{tab.icon}</span>
              <span className="text-xs sm:text-sm">{tab.label}</span>
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="p-4 sm:p-6">
          {activeTab === 'dashboard' && <AdminDashboard />}
          {activeTab === 'mainnet-tether' && <MainnetTetherAdmin />}
          {activeTab === 'transaction-mirror' && <TransactionMirrorAdmin />}
          {activeTab === 'two-way-bridge' && <TwoWayBridgeAdmin />}
          {activeTab === 'channels' && <PaymentChannels />}
          {activeTab === 'state-channels' && <StateChannels />}
          {activeTab === 'channel-admin' && <PaymentChannelAdmin />}
          {activeTab === 'multisig' && <MultiSigAdmin />}
          {activeTab === 'queue' && <TransactionQueue />}
          {activeTab === 'impersonation' && <ImpersonationMode />}
          {activeTab === 'gas' && <GasOptimizer />}
          {activeTab === 'batch' && <BatchOperations />}
          {activeTab === 'templates' && <TransactionTemplates />}
          {activeTab === 'preview' && <TransactionPreview />}
          {activeTab === 'retry' && <TransactionRetry />}
          {activeTab === 'services' && <OffChainServices />}
          {activeTab === 'roles' && <RoleBasedAccess />}
          {activeTab === 'timelock' && <TimeLockedActions />}
          {activeTab === 'wallet' && <WalletDeployment />}
          {activeTab === 'owners' && <OwnerManagement />}
          {activeTab === 'balance' && <WalletBalance />}
          {activeTab === 'backup' && <WalletBackup />}
          {activeTab === 'priority' && <TransactionQueuePriority />}
          {activeTab === 'multichain' && <MultiChainAdmin />}
          {activeTab === 'schedule' && <ScheduledActions />}
          {activeTab === 'audit' && <AuditLogViewer />}
          {activeTab === 'emergency' && <EmergencyControls />}
          {activeTab === 'hardware' && <HardwareWalletSupport />}
          {activeTab === 'permissions' && <FunctionPermissions />}
          {activeTab === 'realtime' && <RealtimeMonitor />}
        </div>
        <TransactionStatusPoller />
        <SessionManager />
      </div>
    </div>
  )
}
