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

// Layout
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'
import { KpiStrip } from '../../design-system/composites'
import type { KpiItem } from '../../design-system/composites'

// 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'
import { Card } from '../../design-system/primitives'

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

const ROUTE_TO_APP = buildRouteToAppMap()

// ─── Build KPI items from scoped route metrics ──────────────────────────────
function buildKpiItems(scopedMetrics: RouteMetricRow[]): KpiItem[] {
  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 throughputPerSec = totalExchanges > 0 ? (totalExchanges / 360).toFixed(1) : '0'
  const activeRoutes = scopedMetrics.length
  const totalRoutes = routeMetrics.length

  const p50 = Math.round(avgLatency * 0.5)
  const p95 = Math.round(avgLatency * 1.4)
  const slaStatus = p99Latency > 300 ? 'BREACH' : 'OK'

  return [
    {
      label: 'Total Throughput',
      value: totalExchanges.toLocaleString(),
      trend: { label: '\u25B2 +8%', variant: 'success' as const },
      subtitle: `${throughputPerSec} msg/s \u00B7 Capacity 39%`,
      sparkline: [44, 46, 45, 47, 48, 46, 47, 48, 46, 47, 48, 47, 46, 47],
      borderColor: 'var(--amber)',
    },
    {
      label: 'System Error Rate',
      value: `${errorRate.toFixed(2)}%`,
      trend: {
        label: errorRate < 1 ? '\u25BC -0.1%' : '\u25B2 +0.4%',
        variant: errorRate < 1 ? 'success' as const : 'error' as const,
      },
      subtitle: `${totalErrors} errors / ${totalExchanges.toLocaleString()} total (6h)`,
      sparkline: [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],
      borderColor: errorRate < 1 ? 'var(--success)' : 'var(--error)',
    },
    {
      label: 'Latency Percentiles',
      value: `${p99Latency}ms`,
      trend: { label: '\u25B2 +28', variant: p99Latency > 300 ? 'error' as const : 'warning' as const },
      subtitle: `P50 ${p50}ms \u00B7 P95 ${p95}ms \u00B7 SLA <300ms P99: ${slaStatus}`,
      borderColor: p99Latency > 300 ? 'var(--warning)' : 'var(--success)',
    },
    {
      label: 'Active Routes',
      value: `${activeRoutes} / ${totalRoutes}`,
      trend: { label: '\u2194 stable', variant: 'muted' as const },
      subtitle: `${activeRoutes} active \u00B7 ${totalRoutes - activeRoutes} stopped`,
      borderColor: 'var(--running)',
    },
    {
      label: 'In-Flight Exchanges',
      value: '23',
      trend: { label: '\u2194', variant: 'muted' as const },
      subtitle: 'High-water: 67 (2h ago)',
      sparkline: [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],
      borderColor: 'var(--amber)',
    },
  ]
}

// ─── 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 (
      <>
        <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>

          <KpiStrip items={buildKpiItems(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="LIVE" color="success" />
              </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>
      </>
    )
  }

  // ── Top level / Application level view ──────────────────────────────────────
  return (
    <>
      <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 */}
        <KpiStrip items={buildKpiItems(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}>
          <Card title="Throughput (msg/s)">
            <AreaChart
              series={convertSeries(throughputSeries)}
              yLabel="msg/s"
              height={200}
              width={500}
              className={styles.chart}
            />
          </Card>

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

          <Card title="Errors by Route">
            <BarChart
              series={ERROR_BAR_SERIES}
              stacked
              height={200}
              width={500}
              className={styles.chart}
            />
          </Card>

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