import { useEffect, useMemo, useState } from 'react'
import { Card } from '@/libs/frontend-ui-primitives'
import { explorerFeaturePages } from '@/data/explorerOperations'
import {
  getMissionControlRelays,
  getMissionControlRelayLabel,
  missionControlApi,
  type MissionControlBridgeStatusResponse,
} from '@/services/api/missionControl'
import { plannerApi, type InternalExecutionPlanResponse, type PlannerCapabilitiesResponse } from '@/services/api/planner'
import { routesApi, type RouteMatrixResponse } from '@/services/api/routes'
import CompactMetricBar from '@/components/common/CompactMetricBar'
import PaginationControls from '@/components/common/PaginationControls'
import SectionTabs, { TabPanel, type SectionTab } from '@/components/common/SectionTabs'
import ClientRelativeTime from '@/components/common/ClientRelativeTime'
import OperationsPageShell, {
  StatusBadge,
  formatNumber,
  truncateMiddle,
} from './OperationsPageShell'

interface OperatorOperationsPageProps {
  initialBridgeStatus?: MissionControlBridgeStatusResponse | null
  initialRouteMatrix?: RouteMatrixResponse | 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'
}

const OPERATOR_RELAY_PAGE_SIZE = 4

export default function OperatorOperationsPage({
  initialBridgeStatus = null,
  initialRouteMatrix = null,
  initialPlannerCapabilities = null,
  initialInternalPlan = null,
}: OperatorOperationsPageProps) {
  const [bridgeStatus, setBridgeStatus] = useState<MissionControlBridgeStatusResponse | null>(initialBridgeStatus)
  const [routeMatrix, setRouteMatrix] = useState<RouteMatrixResponse | null>(initialRouteMatrix)
  const [plannerCapabilities, setPlannerCapabilities] = useState<PlannerCapabilitiesResponse | null>(initialPlannerCapabilities)
  const [internalPlan, setInternalPlan] = useState<InternalExecutionPlanResponse | null>(initialInternalPlan)
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'relays' | 'readiness'>('relays')
  const [relayPage, setRelayPage] = useState(1)
  const page = explorerFeaturePages.operator

  useEffect(() => {
    let cancelled = false

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

      if (cancelled) return

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

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

      if (failedCount === 4) {
        setLoadingError('Operator telemetry is temporarily unavailable from the public explorer APIs.')
      }
    }

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

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

  const relays = useMemo(() => getMissionControlRelays(bridgeStatus), [bridgeStatus])
  const relayEntries = useMemo(() => Object.entries(relays || {}), [relays])

  useEffect(() => {
    setRelayPage(1)
  }, [relayEntries.length])

  const relayPageCount = relayEntries.length ? Math.max(1, Math.ceil(relayEntries.length / OPERATOR_RELAY_PAGE_SIZE)) : 1
  const relayVisibleEntries = relayEntries.slice(
    (relayPage - 1) * OPERATOR_RELAY_PAGE_SIZE,
    relayPage * OPERATOR_RELAY_PAGE_SIZE,
  )
  const providers = plannerCapabilities?.providers || []
  const liveProviders = providers.filter((provider) => provider.live)
  const operatorTabs = useMemo<SectionTab<'relays' | 'readiness'>[]>(
    () => [
      { id: 'relays', label: 'Relay lanes', count: relayEntries.length },
      { id: 'readiness', label: 'Readiness' },
    ],
    [relayEntries.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: 'Fleet', value: bridgeStatus?.data?.status || 'unknown' },
          { label: 'Live routes', value: formatNumber(routeMatrix?.counts?.filteredLiveRoutes) },
          { label: 'Providers', value: formatNumber(liveProviders.length) },
          { label: 'Plan', value: internalPlan?.plannerResponse?.decision || 'unknown' },
        ]}
      />

      <SectionTabs
        tabs={operatorTabs}
        activeTab={activeTab}
        onChange={setActiveTab}
        idPrefix="operator-ops"
        ariaLabel="Operator telemetry sections"
        className="-mx-4 mb-4 px-4"
      />

      <TabPanel idPrefix="operator-ops" tabId="relays" activeTab={activeTab}>
        <Card title="Managed Relay Lanes">
          <div className="space-y-4">
            {relayVisibleEntries.map(([key, relay]) => {
              const snapshot = relay.url_probe?.body || relay.file_snapshot
              const status = snapshot?.status || 'unknown'
              return (
                <div
                  key={key}
                  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">
                        {getMissionControlRelayLabel(key)}
                      </div>
                      <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        {snapshot?.destination?.chain_name || 'Unknown destination'} · queue {formatNumber(snapshot?.queue?.size ?? 0)}
                      </div>
                    </div>
                    <StatusBadge status={status} tone={relayTone(status)} />
                  </div>
                  <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                    Last source poll <ClientRelativeTime value={snapshot?.last_source_poll?.at} suffix=" ago" /> · processed {formatNumber(snapshot?.queue?.processed ?? 0)}
                  </div>
                </div>
              )
            })}
            {relayEntries.length === 0 ? (
              <p className="text-sm text-gray-600 dark:text-gray-400">No relay lane data available.</p>
            ) : null}
            {relayPageCount > 1 ? (
              <PaginationControls
                page={relayPage}
                onPageChange={setRelayPage}
                label="Relay lanes"
                ariaLabel="Operator relay lane pagination"
                hasNextPage={relayPage < relayPageCount}
                className="pt-2"
              />
            ) : null}
          </div>
        </Card>
      </TabPanel>

      <TabPanel idPrefix="operator-ops" tabId="readiness" activeTab={activeTab}>
        <Card title="Execution Readiness">
          <div className="space-y-4">
            <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">Internal execution plan</div>
              <div className="mt-2 flex items-center gap-3">
                <StatusBadge
                  status={internalPlan?.plannerResponse?.decision || 'unknown'}
                  tone={internalPlan?.plannerResponse?.decision === 'direct-pool' ? 'normal' : 'warning'}
                />
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                Contract {truncateMiddle(internalPlan?.execution?.contractAddress)} · {formatNumber(internalPlan?.plannerResponse?.steps?.length)} planner steps
              </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">Live providers</div>
              <div className="mt-3 flex flex-wrap gap-2">
                {liveProviders.map((provider) => (
                  <span
                    key={provider.provider}
                    className="rounded-full bg-primary-50 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-primary-700 dark:bg-primary-900/30 dark:text-primary-300"
                  >
                    {provider.provider}
                  </span>
                ))}
                {liveProviders.length === 0 ? (
                  <span className="text-sm text-gray-600 dark:text-gray-400">No live providers reported.</span>
                ) : null}
              </div>
            </div>
          </div>
        </Card>
      </TabPanel>
    </OperationsPageShell>
  )
}
