import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Card } from '@/libs/frontend-ui-primitives'
import { explorerFeaturePages } from '@/data/explorerOperations'
import {
  routesApi,
  type ExplorerNetwork,
  type MissionControlLiquidityPool,
  type RouteMatrixRoute,
  type RouteMatrixResponse,
} from '@/services/api/routes'
import { missionControlApi, type MissionControlBridgeStatusResponse } from '@/services/api/missionControl'
import { statsApi, type ExplorerStats } from '@/services/api/stats'
import { summarizeChainActivity } from '@/utils/activityContext'
import ExplorerFreshnessDisclosure from '@/components/common/ExplorerFreshnessDisclosure'
import CompactMetricBar from '@/components/common/CompactMetricBar'
import DisclosureSection from '@/components/common/DisclosureSection'
import SectionTabs, { TabPanel } from '@/components/common/SectionTabs'
import SubsystemPosturePanel from '@/components/common/SubsystemPosturePanel'
import { resolveEffectiveFreshness } from '@/utils/explorerFreshness'
import OperationsSurfaceNav from './OperationsSurfaceNav'
import OperationsActionGrid from './OperationsActionGrid'
import ClientRelativeTime from '@/components/common/ClientRelativeTime'

interface RoutesMonitoringPageProps {
  initialRouteMatrix?: RouteMatrixResponse | null
  initialNetworks?: ExplorerNetwork[]
  initialPools?: MissionControlLiquidityPool[]
  initialStats?: ExplorerStats | null
  initialBridgeStatus?: MissionControlBridgeStatusResponse | null
}

const canonicalLiquidityToken = '0x93E66202A11B1772E55407B32B44e5Cd8eda7f22'

function compactAddress(value?: string): string {
  if (!value) return 'Unspecified'
  if (value.length <= 14) return value
  return `${value.slice(0, 6)}...${value.slice(-4)}`
}

function formatUsd(value?: number): string {
  if (typeof value !== 'number' || !Number.isFinite(value)) return 'Unknown'
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  }).format(value)
}

function protocolList(route: RouteMatrixRoute): string {
  const protocols = Array.from(
    new Set((route.legs || []).map((leg) => leg.protocol || leg.executor || '').filter(Boolean))
  )
  return protocols.length > 0 ? protocols.join(', ') : 'Unspecified'
}

function routeAssetPair(route: RouteMatrixRoute): string {
  if (route.routeType === 'bridge') {
    return route.assetSymbol || 'Bridge asset'
  }
  return [route.tokenInSymbol, route.tokenOutSymbol].filter(Boolean).join(' -> ') || 'Swap route'
}

function ActionLink({
  href,
  label,
  external,
}: {
  href: string
  label: string
  external?: boolean
}) {
  const className = 'inline-flex items-center text-sm font-semibold text-primary-600 hover:underline'
  const text = `${label} ->`

  if (external) {
    return (
      <a href={href} className={className} target="_blank" rel="noopener noreferrer">
        {text}
      </a>
    )
  }

  return (
    <Link href={href} className={className}>
      {text}
    </Link>
  )
}

export default function RoutesMonitoringPage({
  initialRouteMatrix = null,
  initialNetworks = [],
  initialPools = [],
  initialStats = null,
  initialBridgeStatus = null,
}: RoutesMonitoringPageProps) {
  const [routeMatrix, setRouteMatrix] = useState<RouteMatrixResponse | null>(initialRouteMatrix)
  const [networks, setNetworks] = useState<ExplorerNetwork[]>(initialNetworks)
  const [pools, setPools] = useState<MissionControlLiquidityPool[]>(initialPools)
  const [stats, setStats] = useState<ExplorerStats | null>(initialStats)
  const [bridgeStatus, setBridgeStatus] = useState<MissionControlBridgeStatusResponse | null>(initialBridgeStatus)
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const [routesTab, setRoutesTab] = useState<'overview' | 'live' | 'backlog'>('overview')
  const page = explorerFeaturePages.routes

  useEffect(() => {
    let cancelled = false

    const load = async () => {
      const [matrixResult, networksResult, poolsResult, statsResult, bridgeResult] = await Promise.allSettled([
        routesApi.getRouteMatrix(),
        routesApi.getNetworks(),
        routesApi.getTokenPools(canonicalLiquidityToken),
        statsApi.get(),
        missionControlApi.getBridgeStatus(),
      ])

      if (cancelled) return

      if (matrixResult.status === 'fulfilled') {
        setRouteMatrix(matrixResult.value)
      }
      if (networksResult.status === 'fulfilled') {
        setNetworks(networksResult.value.networks || [])
      }
      if (poolsResult.status === 'fulfilled') {
        setPools(poolsResult.value.pools || [])
      }
      if (statsResult.status === 'fulfilled') {
        setStats(statsResult.value)
      }
      if (bridgeResult.status === 'fulfilled') {
        setBridgeStatus(bridgeResult.value)
      }

      if (
        matrixResult.status === 'rejected' &&
        networksResult.status === 'rejected' &&
        poolsResult.status === 'rejected' &&
        statsResult.status === 'rejected' &&
        bridgeResult.status === 'rejected'
      ) {
        setLoadingError('Live route inventory is temporarily unavailable.')
      }
    }

    load().catch((error) => {
      if (!cancelled) {
        setLoadingError(
          error instanceof Error ? error.message : 'Live route inventory is temporarily unavailable.'
        )
      }
    })

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

  const liveRoutes = useMemo(() => routeMatrix?.liveRoutes || [], [routeMatrix?.liveRoutes])
  const plannedRoutes = useMemo(
    () => routeMatrix?.blockedOrPlannedRoutes || [],
    [routeMatrix?.blockedOrPlannedRoutes]
  )

  const familyCount = useMemo(() => {
    return new Set(liveRoutes.flatMap((route) => route.aggregatorFamilies || [])).size
  }, [liveRoutes])

  const topRoutes = useMemo(() => {
    const ordered = [...liveRoutes].sort((left, right) => {
      if ((left.routeType || '') !== (right.routeType || '')) {
        return left.routeType === 'bridge' ? -1 : 1
      }
      return (left.label || '').localeCompare(right.label || '')
    })
    return ordered.slice(0, 8)
  }, [liveRoutes])

  const highlightedNetworks = useMemo(() => {
    return networks
      .filter((network) => [138, 1, 651940, 56, 43114].includes(network.chainIdDecimal || 0))
      .sort((left, right) => (left.chainIdDecimal || 0) - (right.chainIdDecimal || 0))
  }, [networks])
  const activityContext = useMemo(
    () =>
      summarizeChainActivity({
        blocks: [],
        transactions: [],
        latestBlockNumber: stats?.latest_block,
        latestBlockTimestamp: null,
        freshness: resolveEffectiveFreshness(stats, bridgeStatus),
        diagnostics: stats?.diagnostics ?? bridgeStatus?.data?.diagnostics ?? null,
      }),
    [bridgeStatus, stats],
  )

  return (
    <div className="container mx-auto px-4 py-4 sm:py-6">
      <div className="mb-4 max-w-4xl">
        <div className="mb-2 inline-flex rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.18em] text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-200">
          {page.eyebrow}
        </div>
        <h1 className="mb-2 text-2xl font-bold text-gray-900 dark:text-white sm:text-3xl">
          {page.title}
        </h1>
        <p className="text-sm leading-6 text-gray-600 dark:text-gray-400">
          {page.description}
        </p>
      </div>

      {page.note ? (
        <DisclosureSection title="Routes scope note" defaultOpen={false} alwaysCollapsible className="mb-4">
          <Card className="border border-amber-200 bg-amber-50/70 dark:border-amber-900/50 dark:bg-amber-950/20">
            <p className="text-sm leading-6 text-amber-950 dark:text-amber-100">
              {page.note}
            </p>
          </Card>
        </DisclosureSection>
      ) : null}

      <OperationsSurfaceNav />

      {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}

      <ExplorerFreshnessDisclosure
        context={activityContext}
        stats={stats}
        bridgeStatus={bridgeStatus}
        title="Freshness & subsystems"
        activityTitle="Routes recency"
        scopeLabel="Route matrix freshness on this page."
      >
        <SubsystemPosturePanel
          className="mt-3"
          subsystems={bridgeStatus?.data?.subsystems}
          title="Route subsystem posture"
          preferredKeys={['rpc_head', 'tx_index', 'stats_summary', 'freshness_queries']}
          scopeLabel="Route inventory subsystem signals."
        />
      </ExplorerFreshnessDisclosure>

      <CompactMetricBar
        metrics={[
          { label: 'Swaps', value: String(routeMatrix?.counts?.liveSwapRoutes ?? liveRoutes.filter((route) => route.routeType === 'swap').length) },
          { label: 'Bridges', value: String(routeMatrix?.counts?.liveBridgeRoutes ?? liveRoutes.filter((route) => route.routeType === 'bridge').length) },
          { label: 'Networks', value: String(networks.length) },
          { label: 'Pools', value: String(pools.length) },
        ]}
      />

      <SectionTabs
        idPrefix="routes"
        ariaLabel="Route views"
        tabs={[
          { id: 'overview', label: 'Overview' },
          { id: 'live', label: 'Live routes', count: topRoutes.length },
          { id: 'backlog', label: 'Backlog', count: plannedRoutes.length },
        ]}
        activeTab={routesTab}
        onChange={setRoutesTab}
        className="mb-4"
      />

      <TabPanel idPrefix="routes" tabId="overview" activeTab={routesTab}>
        <DisclosureSection title="Matrix detail" defaultOpen={false} alwaysCollapsible className="mb-4">
          <div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
            <Card title="Route matrix summary">
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40">
                  <div className="text-xs text-gray-500 dark:text-gray-400">Generated</div>
                  <div className="mt-1 text-base font-semibold text-gray-900 dark:text-white">
                    <ClientRelativeTime value={routeMatrix?.generatedAt} suffix=" ago" />
                  </div>
                  <div className="mt-1 text-xs text-gray-600 dark:text-gray-400">
                    Matrix version {routeMatrix?.version || 'unknown'}
                  </div>
                </div>
                <div className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40">
                  <div className="text-xs text-gray-500 dark:text-gray-400">Updated</div>
                  <div className="mt-1 text-base font-semibold text-gray-900 dark:text-white">
                    <ClientRelativeTime value={routeMatrix?.updated} suffix=" ago" />
                  </div>
                  <div className="mt-1 text-xs text-gray-600 dark:text-gray-400">
                    {familyCount} partner families in live routes
                  </div>
                </div>
                <div className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40">
                  <div className="text-xs text-gray-500 dark:text-gray-400">Live routes</div>
                  <div className="mt-1 text-base font-semibold text-gray-900 dark:text-white">
                    {routeMatrix?.counts?.filteredLiveRoutes ?? liveRoutes.length}
                  </div>
                </div>
                <div className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40">
                  <div className="text-xs text-gray-500 dark:text-gray-400">Planned / blocked</div>
                  <div className="mt-1 text-base font-semibold text-gray-900 dark:text-white">
                    {routeMatrix?.counts?.blockedOrPlannedRoutes ?? plannedRoutes.length}
                  </div>
                </div>
              </div>
            </Card>
            <Card title="Highlighted networks">
              <div className="space-y-2">
                {highlightedNetworks.map((network) => (
                  <div
                    key={`${network.chainIdDecimal}-${network.chainName}`}
                    className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40"
                  >
                    <div className="text-sm font-semibold text-gray-900 dark:text-white">
                      {network.chainName || 'Unknown chain'}
                    </div>
                    <div className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">
                      Chain ID {network.chainIdDecimal ?? 'Unknown'} · {network.shortName || 'n/a'}
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          </div>
        </DisclosureSection>
      </TabPanel>

      <TabPanel idPrefix="routes" tabId="live" activeTab={routesTab}>
        <div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
          <Card title="Live route snapshot">
            <div className="space-y-3">
              {topRoutes.map((route) => (
                <div
                  key={route.routeId}
                  className="rounded-xl border border-gray-200 bg-white p-3 dark:border-gray-700 dark:bg-gray-800"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <div className="text-sm font-semibold text-gray-900 dark:text-white">
                        {route.label || route.routeId}
                      </div>
                      <div className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">
                        {routeAssetPair(route)}
                      </div>
                    </div>
                    <div className="rounded-full bg-primary-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-primary-700 dark:bg-primary-900/30 dark:text-primary-300">
                      {route.routeType || 'route'}
                    </div>
                  </div>
                  <div className="mt-2 text-xs text-gray-600 dark:text-gray-400">
                    {`${route.fromChainId} -> ${route.toChainId} · ${route.hopCount ?? 0} hop${(route.hopCount ?? 0) === 1 ? '' : 's'}`}
                    {' · '}
                    {protocolList(route)}
                  </div>
                </div>
              ))}
            </div>
          </Card>
          <Card title="cUSDT pools">
            <div className="space-y-3">
              {pools.slice(0, 6).map((pool) => (
                <div
                  key={pool.address}
                  className="rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-900/40"
                >
                  <div className="text-sm font-semibold text-gray-900 dark:text-white">
                    {(pool.token0?.symbol || '?') + ' / ' + (pool.token1?.symbol || '?')}
                  </div>
                  <div className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">
                    {pool.dex || 'Unknown DEX'} · TVL {formatUsd(pool.tvl)} · {compactAddress(pool.address)}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </TabPanel>

      <TabPanel idPrefix="routes" tabId="backlog" activeTab={routesTab}>
        <Card title="Planned route backlog">
          <div className="grid gap-3 lg:grid-cols-2">
            {plannedRoutes.slice(0, 8).map((route) => (
              <div
                key={route.routeId}
                className="rounded-xl border border-amber-200 bg-amber-50/70 p-3 dark:border-amber-900/50 dark:bg-amber-950/20"
              >
                <div className="text-sm font-semibold text-gray-900 dark:text-white">
                  {route.routeId}
                </div>
                <div className="mt-1 text-xs text-gray-700 dark:text-gray-300">
                  {(route.tokenInSymbols || []).join(' / ') || routeAssetPair(route)}
                </div>
                <div className="mt-2 text-xs leading-5 text-gray-600 dark:text-gray-400">
                  {route.reason || 'Pending additional deployment or routing work.'}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </TabPanel>

      <OperationsActionGrid actions={page.actions} className="mt-6" />
    </div>
  )
}
