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 { tokensApi } from '@/services/api/tokens'
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 CompactMetricBar from '@/components/common/CompactMetricBar'
import DisclosureSection from '@/components/common/DisclosureSection'
import SectionTabs, { TabPanel, type SectionTab } from '@/components/common/SectionTabs'
import ClientRelativeTime from '@/components/common/ClientRelativeTime'
import OperationsPageShell, {
  StatusBadge,
  formatNumber,
} from './OperationsPageShell'
import TokenListSurfaceNote from '@/components/common/TokenListSurfaceNote'

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 [activeTab, setActiveTab] = useState<'topology' | 'networks'>('topology')
  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(),
          tokensApi.listForSurface('extended', 138).then(({ ok, data }) => ({ tokens: ok ? data : [] })),
          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 systemTabs = useMemo<SectionTab<'topology' | 'networks'>[]>(
    () => [
      { id: 'topology', label: 'Topology' },
      { id: 'networks', label: 'Networks', count: networksConfig?.chains?.length ?? 0 },
    ],
    [networksConfig?.chains?.length],
  )

  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}

      <CompactMetricBar
        metrics={[
          { label: 'Networks', value: formatNumber(networksConfig?.chains?.length) },
          { label: 'Relays', value: formatNumber(relays ? Object.keys(relays).length : 0) },
          { label: 'Tokens', value: formatNumber((tokenList?.tokens || []).length) },
          { label: 'RPC methods', value: formatNumber(capabilities?.http?.supportedMethods?.length) },
        ]}
      />
      <DisclosureSection title="Token list surface note" defaultOpen={false} alwaysCollapsible className="mb-4">
        <TokenListSurfaceNote className="text-xs text-gray-500 dark:text-gray-400" />
      </DisclosureSection>

      <SectionTabs
        tabs={systemTabs}
        activeTab={activeTab}
        onChange={setActiveTab}
        idPrefix="system-ops"
        ariaLabel="System inventory sections"
        className="-mx-4 mb-4 px-4"
      />

      <TabPanel idPrefix="system-ops" tabId="topology" activeTab={activeTab}>
        <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 <ClientRelativeTime value={routeMatrix?.updated} suffix=" ago" /> · {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>
      </TabPanel>

      <TabPanel idPrefix="system-ops" tabId="networks" activeTab={activeTab}>
        <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>
      </TabPanel>
    </OperationsPageShell>
  )
}
