import { useEffect, useMemo, useState } from 'react'
import { Card } from '@/libs/frontend-ui-primitives'
import { explorerFeaturePages } from '@/data/explorerOperations'
import {
  getMissionControlRelays,
  missionControlApi,
  type MissionControlBridgeStatusResponse,
  type MissionControlRelayPayload,
} from '@/services/api/missionControl'
import { plannerApi, type InternalExecutionPlanResponse, type PlannerCapabilitiesResponse } from '@/services/api/planner'
import OperationsPageShell, {
  MetricCard,
  StatusBadge,
  formatNumber,
  relativeAge,
  truncateMiddle,
} from './OperationsPageShell'

interface WethOperationsPageProps {
  initialBridgeStatus?: MissionControlBridgeStatusResponse | null
  initialPlannerCapabilities?: PlannerCapabilitiesResponse | null
  initialInternalPlan?: InternalExecutionPlanResponse | null
}

function relayTone(status?: string): 'normal' | 'warning' | 'danger' {
  const normalized = String(status || 'unknown').toLowerCase()
  if (['degraded', 'stale', 'stopped', 'down'].includes(normalized)) return 'danger'
  if (['paused', 'starting', 'unknown'].includes(normalized)) return 'warning'
  return 'normal'
}

function relaySnapshot(relay: MissionControlRelayPayload | undefined) {
  return relay?.url_probe?.body || relay?.file_snapshot
}

function relaySummary(snapshot: ReturnType<typeof relaySnapshot>) {
  if (!snapshot) return 'destination unknown'
  if (snapshot.status === 'paused' && snapshot.monitoring?.delivery_enabled === false) {
    return `Delivery paused · queue ${formatNumber(snapshot.queue?.size ?? 0)}`
  }
  return `Queue ${formatNumber(snapshot.queue?.size ?? 0)} · ${snapshot.destination?.chain_name || 'destination unknown'}`
}

export default function WethOperationsPage({
  initialBridgeStatus = null,
  initialPlannerCapabilities = null,
  initialInternalPlan = null,
}: WethOperationsPageProps) {
  const [bridgeStatus, setBridgeStatus] = useState<MissionControlBridgeStatusResponse | null>(initialBridgeStatus)
  const [plannerCapabilities, setPlannerCapabilities] = useState<PlannerCapabilitiesResponse | null>(initialPlannerCapabilities)
  const [internalPlan, setInternalPlan] = useState<InternalExecutionPlanResponse | null>(initialInternalPlan)
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const page = explorerFeaturePages.weth

  useEffect(() => {
    let cancelled = false

    const load = async () => {
      const [bridgeResult, capabilitiesResult, planResult] = await Promise.allSettled([
        missionControlApi.getBridgeStatus(),
        plannerApi.getCapabilities(),
        plannerApi.getInternalExecutionPlan(),
      ])

      if (cancelled) return

      if (bridgeResult.status === 'fulfilled') setBridgeStatus(bridgeResult.value)
      if (capabilitiesResult.status === 'fulfilled') setPlannerCapabilities(capabilitiesResult.value)
      if (planResult.status === 'fulfilled') setInternalPlan(planResult.value)

      const failedCount = [bridgeResult, capabilitiesResult, planResult].filter(
        (result) => result.status === 'rejected'
      ).length

      if (failedCount === 3) {
        setLoadingError('WETH operations data is temporarily unavailable from the public explorer APIs.')
      }
    }

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

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

  const relays = useMemo(() => getMissionControlRelays(bridgeStatus), [bridgeStatus])
  const mainnetWeth = relaySnapshot(relays?.mainnet_weth)
  const mainnetCw = relaySnapshot(relays?.mainnet_cw)
  const wethProviders = useMemo(
    () =>
      (plannerCapabilities?.providers || []).filter((provider) =>
        (provider.pairs || []).some(
          (pair) => pair.tokenInSymbol === 'WETH' || pair.tokenOutSymbol === 'WETH'
        )
      ),
    [plannerCapabilities]
  )

  return (
    <OperationsPageShell page={page}>
      <Card className="mb-6 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">
          These WETH references are bridge-lane and public-network representation surfaces, not a claim that Ethereum mainnet WETH contracts are native Chain 138 assets.
          Use this page to review wrapped-asset lane posture, counterpart contracts, and operational dependencies.
        </p>
      </Card>

      {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="Mainnet WETH Lane"
          value={mainnetWeth?.status || 'unknown'}
          description={relaySummary(mainnetWeth)}
          className="border border-sky-200 bg-sky-50/70 dark:border-sky-900/50 dark:bg-sky-950/20"
        />
        <MetricCard
          title="Mainnet cW Lane"
          value={mainnetCw?.status || 'unknown'}
          description={relaySummary(mainnetCw)}
          className="border border-emerald-200 bg-emerald-50/70 dark:border-emerald-900/50 dark:bg-emerald-950/20"
        />
        <MetricCard
          title="WETH Providers"
          value={formatNumber(wethProviders.length)}
          description="Providers that currently publish at least one WETH leg in planner v2."
        />
        <MetricCard
          title="Fallback Decision"
          value={internalPlan?.plannerResponse?.decision || 'unknown'}
          description={
            internalPlan?.execution?.contractAddress
              ? `Execution contract ${truncateMiddle(internalPlan.execution.contractAddress)}`
              : 'Current internal execution-plan posture for a WETH route.'
          }
        />
      </div>

      <div className="mb-8 grid gap-6 lg:grid-cols-[1fr_1fr]">
        <Card title="Mainnet Bridge Lanes">
          <div className="space-y-4">
            {[
              { label: 'Mainnet WETH', snapshot: mainnetWeth },
              { label: 'Mainnet cW', snapshot: mainnetCw },
            ].map(({ label, snapshot }) => (
              <div
                key={label}
                className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40"
              >
                <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <div className="text-base font-semibold text-gray-900 dark:text-white">{label}</div>
                    <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Source {snapshot?.source?.chain_name || 'Unknown'} · destination {snapshot?.destination?.chain_name || 'Unknown'}
                    </div>
                  </div>
                  <StatusBadge status={snapshot?.status || 'unknown'} tone={relayTone(snapshot?.status)} />
                </div>
                <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                  Queue {formatNumber(snapshot?.queue?.size ?? 0)} · last poll {relativeAge(snapshot?.last_source_poll?.at)}
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card title="WETH Route-Ready Providers">
          <div className="space-y-4">
            {wethProviders.map((provider) => {
              const samplePairs = (provider.pairs || [])
                .filter((pair) => pair.tokenInSymbol === 'WETH' || pair.tokenOutSymbol === 'WETH')
                .slice(0, 3)

              return (
                <div
                  key={provider.provider}
                  className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40"
                >
                  <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                      <div className="text-base font-semibold text-gray-900 dark:text-white">
                        {provider.provider}
                      </div>
                      <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        {provider.executionMode || 'unknown mode'} · {(provider.supportedLegTypes || []).join(', ') || 'no leg types'}
                      </div>
                    </div>
                    <StatusBadge status={provider.live ? 'live' : 'inactive'} tone={provider.live ? 'normal' : 'warning'} />
                  </div>
                  <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                    {samplePairs.map((pair) => `${pair.tokenInSymbol} -> ${pair.tokenOutSymbol}`).join(' · ') || 'No WETH pairs published'}
                  </div>
                </div>
              )
            })}
            {wethProviders.length === 0 ? (
              <p className="text-sm text-gray-600 dark:text-gray-400">No WETH-aware providers reported.</p>
            ) : null}
          </div>
        </Card>
      </div>
    </OperationsPageShell>
  )
}
