import { useEffect, useMemo, useState } from 'react'
import { Card } from '@/libs/frontend-ui-primitives'
import { explorerFeaturePages } from '@/data/explorerOperations'
import { configApi, type CapabilitiesResponse, type NetworksConfigResponse, type TokenListResponse } from '@/services/api/config'
import { getMissionControlRelays, missionControlApi, type MissionControlBridgeStatusResponse } from '@/services/api/missionControl'
import { routesApi, type RouteMatrixResponse } from '@/services/api/routes'
import { statsApi, type ExplorerStats } from '@/services/api/stats'
import OperationsPageShell, {
  MetricCard,
  StatusBadge,
  formatNumber,
  relativeAge,
} from './OperationsPageShell'

interface SystemOperationsPageProps {
  initialBridgeStatus?: MissionControlBridgeStatusResponse | null
  initialNetworksConfig?: NetworksConfigResponse | null
  initialTokenList?: TokenListResponse | null
  initialCapabilities?: CapabilitiesResponse | null
  initialRouteMatrix?: RouteMatrixResponse | null
  initialStats?: ExplorerStats | null
}

export default function SystemOperationsPage({
  initialBridgeStatus = null,
  initialNetworksConfig = null,
  initialTokenList = null,
  initialCapabilities = null,
  initialRouteMatrix = null,
  initialStats = null,
}: SystemOperationsPageProps) {
  const [bridgeStatus, setBridgeStatus] = useState<MissionControlBridgeStatusResponse | null>(initialBridgeStatus)
  const [networksConfig, setNetworksConfig] = useState<NetworksConfigResponse | null>(initialNetworksConfig)
  const [tokenList, setTokenList] = useState<TokenListResponse | null>(initialTokenList)
  const [capabilities, setCapabilities] = useState<CapabilitiesResponse | null>(initialCapabilities)
  const [routeMatrix, setRouteMatrix] = useState<RouteMatrixResponse | null>(initialRouteMatrix)
  const [stats, setStats] = useState<ExplorerStats | null>(initialStats)
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const page = explorerFeaturePages.system

  useEffect(() => {
    let cancelled = false

    const load = async () => {
      const [bridgeResult, networksResult, tokenListResult, capabilitiesResult, routesResult, statsResult] =
        await Promise.allSettled([
          missionControlApi.getBridgeStatus(),
          configApi.getNetworks(),
          configApi.getTokenList(),
          configApi.getCapabilities(),
          routesApi.getRouteMatrix(),
          statsApi.get(),
        ])

      if (cancelled) return

      if (bridgeResult.status === 'fulfilled') setBridgeStatus(bridgeResult.value)
      if (networksResult.status === 'fulfilled') setNetworksConfig(networksResult.value)
      if (tokenListResult.status === 'fulfilled') setTokenList(tokenListResult.value)
      if (capabilitiesResult.status === 'fulfilled') setCapabilities(capabilitiesResult.value)
      if (routesResult.status === 'fulfilled') setRouteMatrix(routesResult.value)
      if (statsResult.status === 'fulfilled') setStats(statsResult.value)

      const failedCount = [
        bridgeResult,
        networksResult,
        tokenListResult,
        capabilitiesResult,
        routesResult,
        statsResult,
      ].filter((result) => result.status === 'rejected').length

      if (failedCount === 6) {
        setLoadingError('System inventory data is temporarily unavailable from the public explorer APIs.')
      }
    }

    load().catch((error) => {
      if (!cancelled) {
        setLoadingError(error instanceof Error ? error.message : 'System inventory data is temporarily unavailable from the public explorer APIs.')
      }
    })

    return () => {
      cancelled = true
    }
  }, [])

  const relays = useMemo(() => getMissionControlRelays(bridgeStatus), [bridgeStatus])
  const chainStatus = bridgeStatus?.data?.chains?.['138']
  const chainCoverage = useMemo(
    () => new Set((tokenList?.tokens || []).map((token) => token.chainId).filter(Boolean)).size,
    [tokenList]
  )

  return (
    <OperationsPageShell page={page}>
      {loadingError ? (
        <Card className="mb-6 border border-red-200 bg-red-50/70 dark:border-red-900/50 dark:bg-red-950/20">
          <p className="text-sm leading-6 text-red-900 dark:text-red-100">{loadingError}</p>
        </Card>
      ) : null}

      <div className="mb-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard
          title="Published Networks"
          value={formatNumber(networksConfig?.chains?.length)}
          description={`Default chain ${networksConfig?.defaultChainId ?? 'unknown'} in wallet onboarding.`}
          className="border border-sky-200 bg-sky-50/70 dark:border-sky-900/50 dark:bg-sky-950/20"
        />
        <MetricCard
          title="Relay Lanes"
          value={formatNumber(relays ? Object.keys(relays).length : 0)}
          description={`${bridgeStatus?.data?.status || 'unknown'} public bridge posture across managed lanes.`}
          className="border border-emerald-200 bg-emerald-50/70 dark:border-emerald-900/50 dark:bg-emerald-950/20"
        />
        <MetricCard
          title="Token Coverage"
          value={formatNumber((tokenList?.tokens || []).length)}
          description={`${formatNumber(chainCoverage)} chain catalogs served through the public token list.`}
        />
        <MetricCard
          title="RPC Methods"
          value={formatNumber(capabilities?.http?.supportedMethods?.length)}
          description={`${formatNumber(capabilities?.tracing?.supportedMethods?.length)} tracing methods published.`}
        />
      </div>

      <div className="mb-8 grid gap-6 lg:grid-cols-[1fr_1fr]">
        <Card title="Topology Snapshot">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <div className="text-sm text-gray-500 dark:text-gray-400">Chain 138 RPC</div>
              <div className="mt-2 flex items-center gap-3">
                <StatusBadge status={chainStatus?.status || 'unknown'} tone={chainStatus?.status === 'operational' ? 'normal' : 'warning'} />
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                Head age {chainStatus?.head_age_sec != null ? `${Math.round(chainStatus.head_age_sec)}s` : 'Unknown'} · latency {chainStatus?.latency_ms != null ? `${Math.round(chainStatus.latency_ms)}ms` : 'Unknown'}
              </div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <div className="text-sm text-gray-500 dark:text-gray-400">Route matrix</div>
              <div className="mt-2 text-lg font-semibold text-gray-900 dark:text-white">
                {formatNumber(routeMatrix?.counts?.filteredLiveRoutes)} live routes
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                Updated {relativeAge(routeMatrix?.updated)} · {formatNumber(routeMatrix?.counts?.blockedOrPlannedRoutes)} planned or blocked
              </div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <div className="text-sm text-gray-500 dark:text-gray-400">Explorer index</div>
              <div className="mt-2 text-lg font-semibold text-gray-900 dark:text-white">
                {formatNumber(stats?.total_blocks)} blocks
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                {formatNumber(stats?.total_transactions)} transactions · {formatNumber(stats?.total_addresses)} addresses
              </div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <div className="text-sm text-gray-500 dark:text-gray-400">Wallet compatibility</div>
              <div className="mt-2 flex items-center gap-3">
                <StatusBadge
                  status={
                    capabilities?.walletSupport?.walletAddEthereumChain && capabilities?.walletSupport?.walletWatchAsset
                      ? 'ready'
                      : 'partial'
                  }
                  tone={
                    capabilities?.walletSupport?.walletAddEthereumChain && capabilities?.walletSupport?.walletWatchAsset
                      ? 'normal'
                      : 'warning'
                  }
                />
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                Public capabilities JSON is wired for chain-add and token-add flows.
              </div>
            </div>
          </div>
        </Card>

        <Card title="Network Inventory">
          <div className="grid gap-3 sm:grid-cols-2">
            {(networksConfig?.chains || []).map((chain) => (
              <div
                key={`${chain.chainIdDecimal}-${chain.shortName}`}
                className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40"
              >
                <div className="text-base font-semibold text-gray-900 dark:text-white">
                  {chain.chainName || chain.shortName || `Chain ${chain.chainIdDecimal}`}
                </div>
                <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                  Chain ID {chain.chainIdDecimal ?? 'Unknown'} · short name {chain.shortName || 'Unknown'}
                </div>
              </div>
            ))}
            {(networksConfig?.chains || []).length === 0 ? (
              <p className="text-sm text-gray-600 dark:text-gray-400">No network inventory available.</p>
            ) : null}
          </div>
        </Card>
      </div>
    </OperationsPageShell>
  )
}
