import { useMemo } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './Routes.module.css'

// Layout
import { AppShell } from '../../design-system/layout/AppShell/AppShell'
import { Sidebar } from '../../design-system/layout/Sidebar/Sidebar'
import { TopBar } from '../../design-system/layout/TopBar/TopBar'

// Composites
import { AreaChart } from '../../design-system/composites/AreaChart/AreaChart'
import { LineChart } from '../../design-system/composites/LineChart/LineChart'
import { BarChart } from '../../design-system/composites/BarChart/BarChart'
import { DataTable } from '../../design-system/composites/DataTable/DataTable'
import type { Column } from '../../design-system/composites/DataTable/types'
import { RouteFlow } from '../../design-system/composites/RouteFlow/RouteFlow'
import type { RouteNode } from '../../design-system/composites/RouteFlow/RouteFlow'

// Primitives
import { Sparkline } from '../../design-system/primitives/Sparkline/Sparkline'
import { MonoText } from '../../design-system/primitives/MonoText/MonoText'
import { Badge } from '../../design-system/primitives/Badge/Badge'

// Mock data
import {
  throughputSeries,
  latencySeries,
  errorCountSeries,
  routeMetrics,
  type RouteMetricRow,
} from '../../mocks/metrics'
import { routes } from '../../mocks/routes'
import { SIDEBAR_APPS, buildRouteToAppMap } from '../../mocks/sidebar'

const ROUTE_TO_APP = buildRouteToAppMap()

// ─── KPI Header Strip (matches mock-v3-metrics-dashboard) ────────────────────
function KpiHeader({ scopedMetrics }: { scopedMetrics: RouteMetricRow[] }) {
  const totalExchanges = scopedMetrics.reduce((sum, r) => sum + r.exchangeCount, 0)
  const totalErrors = scopedMetrics.reduce((sum, r) => sum + r.errorCount, 0)
  const errorRate = totalExchanges > 0 ? ((totalErrors / totalExchanges) * 100) : 0
  const avgLatency = scopedMetrics.length > 0
    ? Math.round(scopedMetrics.reduce((sum, r) => sum + r.avgDurationMs, 0) / scopedMetrics.length)
    : 0
  const p99Latency = scopedMetrics.length > 0
    ? Math.max(...scopedMetrics.map((r) => r.p99DurationMs))
    : 0
  const avgSuccessRate = scopedMetrics.length > 0
    ? Number((scopedMetrics.reduce((sum, r) => sum + r.successRate, 0) / scopedMetrics.length).toFixed(1))
    : 0
  const throughputPerSec = totalExchanges > 0 ? (totalExchanges / 360).toFixed(1) : '0'
  const activeRoutes = scopedMetrics.length
  const totalRoutes = routeMetrics.length

  return (
    <div className={styles.kpiStrip}>
      {/* Card 1: Total Throughput */}
      <div className={`${styles.kpiCard} ${styles.kpiCardAmber}`}>
        <div className={styles.kpiLabel}>Total Throughput</div>
        <div className={styles.kpiValueRow}>
          <span className={`${styles.kpiValue} ${styles.kpiValueAmber}`}>{totalExchanges.toLocaleString()}</span>
          <span className={styles.kpiUnit}>msg/shift</span>
          <span className={`${styles.kpiTrend} ${styles.trendUpGood}`}>&#9650; +8%</span>
        </div>
        <div className={styles.kpiDetail}>
          <span className={styles.kpiDetailStrong}>{throughputPerSec}</span> msg/s · Capacity 39%
        </div>
        <div className={styles.kpiSparkline}>
          <Sparkline data={[44, 46, 45, 47, 48, 46, 47, 48, 46, 47, 48, 47, 46, 47]} color="var(--amber)" width={200} height={32} />
        </div>
      </div>

      {/* Card 2: System Error Rate */}
      <div className={`${styles.kpiCard} ${errorRate < 1 ? styles.kpiCardGreen : styles.kpiCardError}`}>
        <div className={styles.kpiLabel}>System Error Rate</div>
        <div className={styles.kpiValueRow}>
          <span className={`${styles.kpiValue} ${errorRate < 1 ? styles.kpiValueGreen : styles.kpiValueError}`}>{errorRate.toFixed(2)}%</span>
          <span className={`${styles.kpiTrend} ${errorRate < 1 ? styles.trendDownGood : styles.trendUpBad}`}>
            {errorRate < 1 ? '\u25BC -0.1%' : '\u25B2 +0.4%'}
          </span>
        </div>
        <div className={styles.kpiDetail}>
          <span className={styles.kpiDetailStrong}>{totalErrors}</span> errors / <span className={styles.kpiDetailStrong}>{totalExchanges.toLocaleString()}</span> total (6h)
        </div>
        <div className={styles.kpiSparkline}>
          <Sparkline data={[1.2, 1.8, 1.5, 2.1, 2.4, 2.2, 2.5, 2.6, 2.7, 2.8, 2.7, 2.9, 2.8, errorRate]} color={errorRate < 1 ? 'var(--success)' : 'var(--error)'} width={200} height={32} />
        </div>
      </div>

      {/* Card 3: Latency Percentiles */}
      <div className={`${styles.kpiCard} ${p99Latency > 300 ? styles.kpiCardWarn : styles.kpiCardGreen}`}>
        <div className={styles.kpiLabel}>Latency Percentiles</div>
        <div className={styles.latencyValues}>
          <div className={styles.latencyItem}>
            <span className={styles.latencyLabel}>P50</span>
            <span className={`${styles.latencyVal} ${styles.latValGreen}`}>{Math.round(avgLatency * 0.5)}ms</span>
            <span className={`${styles.latencyTrend} ${styles.trendDownGood}`}>&#9660;3</span>
          </div>
          <div className={styles.latencyItem}>
            <span className={styles.latencyLabel}>P95</span>
            <span className={`${styles.latencyVal} ${avgLatency > 150 ? styles.latValAmber : styles.latValGreen}`}>{Math.round(avgLatency * 1.4)}ms</span>
            <span className={`${styles.latencyTrend} ${styles.trendUpBad}`}>&#9650;12</span>
          </div>
          <div className={styles.latencyItem}>
            <span className={styles.latencyLabel}>P99</span>
            <span className={`${styles.latencyVal} ${p99Latency > 300 ? styles.latValRed : styles.latValAmber}`}>{p99Latency}ms</span>
            <span className={`${styles.latencyTrend} ${styles.trendUpBad}`}>&#9650;28</span>
          </div>
        </div>
        <div className={styles.kpiDetail}>
          SLA: &lt;300ms P99 · {p99Latency > 300
            ? <span style={{ color: 'var(--error)', fontWeight: 600 }}>BREACH</span>
            : <span style={{ color: 'var(--success)', fontWeight: 600 }}>OK</span>}
        </div>
      </div>

      {/* Card 4: Active Routes */}
      <div className={`${styles.kpiCard} ${styles.kpiCardTeal}`}>
        <div className={styles.kpiLabel}>Active Routes</div>
        <div className={styles.kpiValueRow}>
          <span className={`${styles.kpiValue} ${styles.kpiValueTeal}`}>{activeRoutes}</span>
          <span className={styles.kpiUnit}>of {totalRoutes}</span>
          <span className={`${styles.kpiTrend} ${styles.trendFlat}`}>&#8596; stable</span>
        </div>
        <div className={styles.donutWrap}>
          <svg viewBox="0 0 36 36" width="40" height="40">
            <circle cx="18" cy="18" r="15.9" fill="none" stroke="var(--bg-inset)" strokeWidth="3" />
            <circle cx="18" cy="18" r="15.9" fill="none" stroke="var(--running)" strokeWidth="3"
              strokeDasharray={`${(activeRoutes / totalRoutes) * 100} ${100 - (activeRoutes / totalRoutes) * 100}`}
              strokeDashoffset="25" strokeLinecap="round" />
          </svg>
          <div className={styles.donutLegend}>
            <span className={styles.donutLegendActive}>{activeRoutes} active</span>
            <span>{totalRoutes - activeRoutes} stopped</span>
          </div>
        </div>
      </div>

      {/* Card 5: In-Flight Exchanges */}
      <div className={`${styles.kpiCard} ${styles.kpiCardAmber}`}>
        <div className={styles.kpiLabel}>In-Flight Exchanges</div>
        <div className={styles.kpiValueRow}>
          <span className={styles.kpiValue}>23</span>
          <span className={`${styles.kpiTrend} ${styles.trendFlat}`}>&#8596;</span>
        </div>
        <div className={styles.kpiDetail}>
          High-water: <span className={styles.kpiDetailStrong}>67</span> (2h ago)
        </div>
        <div className={styles.kpiSparkline}>
          <Sparkline data={[16, 14, 18, 12, 10, 15, 8, 6, 4, 3, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 18, 16, 18, 20, 18, 23]} color="var(--amber)" width={200} height={32} />
        </div>
      </div>
    </div>
  )
}

// ─── Route metric row with id field (required by DataTable) ──────────────────
type RouteMetricRowWithId = RouteMetricRow & { id: string }

// ─── Processor metrics types and generator ───────────────────────────────────

interface ProcessorMetric {
  name: string
  type: string
  invocations: number
  avgDurationMs: number
  p99DurationMs: number
  errorCount: number
  errorRate: number
  sparkline: number[]
}

type ProcessorMetricWithId = ProcessorMetric & { id: string }

function generateProcessorMetrics(processors: string[], routeExchangeCount: number): ProcessorMetric[] {
  return processors.map((proc, i) => {
    const name = proc
    const type = proc.startsWith('from(') ? 'consumer'
      : proc.startsWith('to(') ? 'producer'
      : proc.startsWith('enrich(') ? 'enricher'
      : proc.startsWith('validate(') || proc.startsWith('check(') ? 'validator'
      : proc.startsWith('unmarshal(') || proc.startsWith('marshal(') ? 'transformer'
      : proc.startsWith('route(') || proc.startsWith('choice(') ? 'router'
      : 'processor'
    const invocations = routeExchangeCount
    const avgBase = 10 + (i * 15) + (proc.includes('enrich') ? 40 : 0) + (proc.includes('http') ? 80 : 0)
    const avgDurationMs = avgBase + Math.round(Math.sin(i * 2.1) * 10)
    const p99DurationMs = Math.round(avgDurationMs * 2.5)
    const errorCount = proc.includes('enrich') || proc.includes('http') ? Math.round(invocations * 0.01) : Math.round(invocations * 0.001)
    const errorRate = Number(((errorCount / invocations) * 100).toFixed(2))
    const sparkline = Array.from({ length: 14 }, (_, j) => avgDurationMs + Math.round(Math.sin(j * 0.8 + i) * avgDurationMs * 0.15))
    return { name, type, invocations, avgDurationMs, p99DurationMs, errorCount, errorRate, sparkline }
  })
}

// ─── Map processor type to RouteNode type ────────────────────────────────────
function toRouteNodeType(procType: string): RouteNode['type'] {
  switch (procType) {
    case 'consumer': return 'from'
    case 'producer': return 'to'
    case 'enricher': return 'process'
    case 'validator': return 'process'
    case 'transformer': return 'process'
    case 'router': return 'choice'
    default: return 'process'
  }
}

// ─── Processor type badge classes ────────────────────────────────────────────
const TYPE_STYLE_MAP: Record<string, string> = {
  consumer: styles.typeConsumer,
  producer: styles.typeProducer,
  enricher: styles.typeEnricher,
  validator: styles.typeValidator,
  transformer: styles.typeTransformer,
  router: styles.typeRouter,
  processor: styles.typeProcessor,
}

// ─── Route performance table columns ──────────────────────────────────────────
const ROUTE_COLUMNS: Column<RouteMetricRowWithId>[] = [
  {
    key: 'routeName',
    header: 'Route',
    sortable: true,
    render: (_, row) => (
      <span className={styles.routeNameCell}>{row.routeName}</span>
    ),
  },
  {
    key: 'appId',
    header: 'Application',
    sortable: true,
    render: (_, row) => (
      <span className={styles.appCell}>{row.appId}</span>
    ),
  },
  {
    key: 'exchangeCount',
    header: 'Exchanges',
    sortable: true,
    render: (_, row) => (
      <MonoText size="sm">{row.exchangeCount.toLocaleString()}</MonoText>
    ),
  },
  {
    key: 'successRate',
    header: 'Success %',
    sortable: true,
    render: (_, row) => {
      const cls = row.successRate >= 99 ? styles.rateGood : row.successRate >= 97 ? styles.rateWarn : styles.rateBad
      return <MonoText size="sm" className={cls}>{row.successRate.toFixed(1)}%</MonoText>
    },
  },
  {
    key: 'avgDurationMs',
    header: 'Avg Duration',
    sortable: true,
    render: (_, row) => (
      <MonoText size="sm">{row.avgDurationMs}ms</MonoText>
    ),
  },
  {
    key: 'p99DurationMs',
    header: 'p99 Duration',
    sortable: true,
    render: (_, row) => {
      const cls = row.p99DurationMs > 300 ? styles.rateBad : row.p99DurationMs > 200 ? styles.rateWarn : styles.rateGood
      return <MonoText size="sm" className={cls}>{row.p99DurationMs}ms</MonoText>
    },
  },
  {
    key: 'errorCount',
    header: 'Errors',
    sortable: true,
    render: (_, row) => (
      <MonoText size="sm" className={row.errorCount > 10 ? styles.rateBad : styles.rateNeutral}>
        {row.errorCount}
      </MonoText>
    ),
  },
  {
    key: 'sparkline',
    header: 'Trend',
    render: (_, row) => (
      <Sparkline data={row.sparkline} width={80} height={24} />
    ),
  },
]

// ─── Processor performance table columns ─────────────────────────────────────
const PROCESSOR_COLUMNS: Column<ProcessorMetricWithId>[] = [
  {
    key: 'name',
    header: 'Processor',
    sortable: true,
    render: (_, row) => (
      <span className={styles.routeNameCell}>{row.name}</span>
    ),
  },
  {
    key: 'type',
    header: 'Type',
    sortable: true,
    render: (_, row) => (
      <span className={`${styles.processorType} ${TYPE_STYLE_MAP[row.type] ?? styles.typeProcessor}`}>
        {row.type}
      </span>
    ),
  },
  {
    key: 'invocations',
    header: 'Invocations',
    sortable: true,
    render: (_, row) => (
      <MonoText size="sm">{row.invocations.toLocaleString()}</MonoText>
    ),
  },
  {
    key: 'avgDurationMs',
    header: 'Avg Duration',
    sortable: true,
    render: (_, row) => {
      const cls = row.avgDurationMs > 200 ? styles.rateBad : row.avgDurationMs > 100 ? styles.rateWarn : styles.rateGood
      return <MonoText size="sm" className={cls}>{row.avgDurationMs}ms</MonoText>
    },
  },
  {
    key: 'p99DurationMs',
    header: 'p99 Duration',
    sortable: true,
    render: (_, row) => {
      const cls = row.p99DurationMs > 300 ? styles.rateBad : row.p99DurationMs > 200 ? styles.rateWarn : styles.rateGood
      return <MonoText size="sm" className={cls}>{row.p99DurationMs}ms</MonoText>
    },
  },
  {
    key: 'errorCount',
    header: 'Errors',
    sortable: true,
    render: (_, row) => (
      <MonoText size="sm" className={row.errorCount > 10 ? styles.rateBad : styles.rateNeutral}>
        {row.errorCount}
      </MonoText>
    ),
  },
  {
    key: 'errorRate',
    header: 'Error Rate',
    sortable: true,
    render: (_, row) => {
      const cls = row.errorRate > 1 ? styles.rateBad : row.errorRate > 0.5 ? styles.rateWarn : styles.rateGood
      return <MonoText size="sm" className={cls}>{row.errorRate}%</MonoText>
    },
  },
  {
    key: 'sparkline',
    header: 'Trend',
    render: (_, row) => (
      <Sparkline data={row.sparkline} width={80} height={24} />
    ),
  },
]

// ─── Build bar chart data from error series ────────────────────────────────────
function buildErrorBarSeries() {
  const sampleInterval = 5
  return errorCountSeries.map((s) => ({
    label: s.label,
    data: s.data
      .filter((_, i) => i % sampleInterval === 0)
      .map((pt) => ({
        x: pt.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        y: Math.round(pt.value),
      })),
  }))
}

// ─── Build volume area chart (derived from throughput) ─────────────────────────
function buildVolumeSeries() {
  return throughputSeries.map((s) => ({
    label: s.label,
    data: s.data.map((pt) => ({
      x: pt.timestamp,
      y: Math.round(pt.value * 60),
    })),
  }))
}

const ERROR_BAR_SERIES = buildErrorBarSeries()
const VOLUME_SERIES = buildVolumeSeries()

// Convert MetricSeries (from mocks) to ChartSeries format
function convertSeries(series: typeof throughputSeries) {
  return series.map((s) => ({
    label: s.label,
    data: s.data.map((pt) => ({ x: pt.timestamp, y: pt.value })),
  }))
}

// ─── Routes page ──────────────────────────────────────────────────────────────
export function Routes() {
  const navigate = useNavigate()
  const { appId, routeId } = useParams<{ appId: string; routeId: string }>()

  // ── Breadcrumbs ─────────────────────────────────────────────────────────────
  const breadcrumb = useMemo(() => {
    if (routeId && appId) {
      return [
        { label: 'Routes', href: '/routes' },
        { label: appId, href: `/routes/${appId}` },
        { label: routeId },
      ]
    }
    if (appId) {
      return [
        { label: 'Routes', href: '/routes' },
        { label: appId },
      ]
    }
    return [{ label: 'Routes' }]
  }, [appId, routeId])

  // ── Data filtering ──────────────────────────────────────────────────────────
  const filteredMetrics = useMemo(() => {
    const data = appId
      ? routeMetrics.filter((r) => r.appId === appId)
      : routeMetrics
    return data.map((r) => ({ ...r, id: r.routeId }))
  }, [appId])

  // ── Route detail data ───────────────────────────────────────────────────────
  const routeDef = useMemo(() => {
    if (!routeId) return null
    return routes.find((r) => r.id === routeId) ?? null
  }, [routeId])

  const processorMetrics = useMemo<ProcessorMetricWithId[]>(() => {
    if (!routeDef) return []
    return generateProcessorMetrics(routeDef.processors, routeDef.exchangeCount).map((pm, i) => ({
      ...pm,
      id: `proc-${i}`,
    }))
  }, [routeDef])

  const routeFlowNodes = useMemo<RouteNode[]>(() => {
    if (!processorMetrics.length) return []
    return processorMetrics.map((pm) => ({
      name: pm.name,
      type: toRouteNodeType(pm.type),
      durationMs: pm.avgDurationMs,
      status: pm.errorRate > 1 ? 'fail' as const : pm.avgDurationMs > 150 ? 'slow' as const : 'ok' as const,
    }))
  }, [processorMetrics])

  // Scoped metrics for KPI header
  const scopedMetricsForKpi = useMemo(() => {
    if (routeId) return routeMetrics.filter((r) => r.routeId === routeId)
    if (appId) return routeMetrics.filter((r) => r.appId === appId)
    return routeMetrics
  }, [appId, routeId])

  // ── Route detail view ───────────────────────────────────────────────────────
  if (routeId && appId && routeDef) {
    return (
      <AppShell sidebar={<Sidebar apps={SIDEBAR_APPS} />}>
        <TopBar
          breadcrumb={breadcrumb}
          environment="PRODUCTION"
          user={{ name: 'hendrik' }}
        />
        <div className={styles.content}>
          <div className={styles.refreshIndicator}>
            <span className={styles.refreshDot} />
            <span className={styles.refreshText}>Auto-refresh: 30s</span>
          </div>

          <KpiHeader scopedMetrics={scopedMetricsForKpi} />

          {/* Processor Performance table */}
          <div className={styles.tableSection}>
            <div className={styles.tableHeader}>
              <span className={styles.tableTitle}>Processor Performance</span>
              <div className={styles.tableRight}>
                <span className={styles.tableMeta}>{processorMetrics.length} processors</span>
                <Badge label="SHIFT" color="primary" />
              </div>
            </div>
            <DataTable
              columns={PROCESSOR_COLUMNS}
              data={processorMetrics}
              sortable
            />
          </div>

          {/* Route Flow diagram */}
          <div className={styles.routeFlowSection}>
            <div className={styles.tableHeader}>
              <span className={styles.tableTitle}>Route Flow</span>
            </div>
            <RouteFlow nodes={routeFlowNodes} />
          </div>
        </div>
      </AppShell>
    )
  }

  // ── Top level / Application level view ──────────────────────────────────────
  return (
    <AppShell sidebar={<Sidebar apps={SIDEBAR_APPS} />}>
      <TopBar
        breadcrumb={breadcrumb}
        environment="PRODUCTION"
        user={{ name: 'hendrik' }}
      />
      <div className={styles.content}>
        <div className={styles.refreshIndicator}>
          <span className={styles.refreshDot} />
          <span className={styles.refreshText}>Auto-refresh: 30s</span>
        </div>

        {/* KPI header cards */}
        <KpiHeader scopedMetrics={scopedMetricsForKpi} />

        {/* Per-route performance table */}
        <div className={styles.tableSection}>
          <div className={styles.tableHeader}>
            <span className={styles.tableTitle}>Per-Route Performance</span>
            <div className={styles.tableRight}>
              <span className={styles.tableMeta}>{filteredMetrics.length} routes</span>
              <Badge label="SHIFT" color="primary" />
            </div>
          </div>
          <DataTable
            columns={ROUTE_COLUMNS}
            data={filteredMetrics}
            sortable
            onRowClick={(row) => {
              const rowAppId = appId ?? ROUTE_TO_APP.get(row.routeId) ?? row.routeId
              navigate(`/routes/${rowAppId}/${row.routeId}`)
            }}
          />
        </div>

        {/* 2x2 chart grid */}
        <div className={styles.chartGrid}>
          <div className={styles.chartCard}>
            <div className={styles.chartTitle}>Throughput (msg/s)</div>
            <AreaChart
              series={convertSeries(throughputSeries)}
              yLabel="msg/s"
              height={200}
              width={500}
              className={styles.chart}
            />
          </div>

          <div className={styles.chartCard}>
            <div className={styles.chartTitle}>Latency (ms)</div>
            <LineChart
              series={convertSeries(latencySeries)}
              yLabel="ms"
              threshold={{ value: 300, label: 'SLA 300ms' }}
              height={200}
              width={500}
              className={styles.chart}
            />
          </div>

          <div className={styles.chartCard}>
            <div className={styles.chartTitle}>Errors by Route</div>
            <BarChart
              series={ERROR_BAR_SERIES}
              stacked
              height={200}
              width={500}
              className={styles.chart}
            />
          </div>

          <div className={styles.chartCard}>
            <div className={styles.chartTitle}>Message Volume (msg/min)</div>
            <AreaChart
              series={VOLUME_SERIES}
              yLabel="msg/min"
              height={200}
              width={500}
              className={styles.chart}
            />
          </div>
        </div>
      </div>
    </AppShell>
  )
}
