'use client'

/**
 * AIModelStatus — AI provider route health grid
 * Sprint 5R S9: 設計稿 L531-545
 * @created 2026-04-09 Claude Opus 4.6 Asia/Taipei
 */

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

interface ModelInfo {
  name: string
  role: 'primary' | 'backup' | 'local' | 'agent' | 'provider'
  status: 'up' | 'down' | 'degraded' | 'unknown'
  latencyMs?: number | null
  diagnosisCode?: string | null
  retryAfterSeconds?: number | null
  isCooldown?: boolean
}

interface HealthComponent {
  status?: 'up' | 'down' | 'degraded'
  latency_ms?: number | null
  provider_name?: string | null
  diagnosis_code?: string | null
  retry_after_seconds?: number | null
  is_cooldown?: boolean
  error?: string | null
}

interface HealthResponse {
  components?: Record<string, HealthComponent>
  ollama_route_order?: string[]
}

const PROVIDER_LABELS: Record<string, string> = {
  ollama_gcp_a: 'GCP-A',
  ollama_gcp_b: 'GCP-B',
  ollama_local: '111',
  openclaw: 'OpenClaw',
}

const PROVIDER_ROLES: Record<string, ModelInfo['role']> = {
  ollama_gcp_a: 'primary',
  ollama_gcp_b: 'backup',
  ollama_local: 'local',
  openclaw: 'agent',
}

interface RouteSummary {
  tone: 'healthy' | 'warning' | 'critical' | 'unknown'
  title: string
  detail: string
}

function statusColor(status: ModelInfo['status']) {
  if (status === 'up') return '#22C55E'
  if (status === 'degraded') return '#F59E0B'
  if (status === 'down') return '#cc2200'
  return '#87867f'
}

function summaryToneStyle(tone: RouteSummary['tone']) {
  if (tone === 'healthy') {
    return { border: '#b8d8bd', background: '#f0faf2', color: '#17602a' }
  }
  if (tone === 'warning') {
    return { border: '#d9b36f', background: '#fff7e8', color: '#7a4d05' }
  }
  if (tone === 'critical') {
    return { border: '#e1aaa2', background: '#fff3f1', color: '#9f2f25' }
  }
  return { border: '#d8d3c7', background: '#faf9f3', color: '#5f5b52' }
}

function modelDetail(model: ModelInfo, t: ReturnType<typeof useTranslations>) {
  if (typeof model.latencyMs === 'number' && model.status === 'up') {
    return `${Math.round(model.latencyMs)}ms`
  }
  if (model.isCooldown) {
    const seconds = Math.max(0, Math.round(model.retryAfterSeconds ?? 0))
    return seconds > 0
      ? t('aiModelHealth.cooldownSeconds', { seconds })
      : t('aiModelHealth.cooldown')
  }
  if (model.diagnosisCode === 'local_proxy_upstream_unreachable') {
    return t('aiModelHealth.localProxy')
  }
  if (model.diagnosisCode === 'endpoint_timeout') {
    return t('aiModelHealth.timeout')
  }
  if (model.diagnosisCode === 'endpoint_network_unreachable') {
    return t('aiModelHealth.network')
  }
  if (model.diagnosisCode === 'endpoint_connection_refused') {
    return t('aiModelHealth.refused')
  }
  return t(`aiModelRoles.${model.role}` as never)
}

function buildRouteSummary(
  components: Record<string, HealthComponent>,
  t: ReturnType<typeof useTranslations>,
): RouteSummary {
  const aggregate = components.ollama
  const selected = aggregate?.provider_name
  const selectedLabel = selected ? (PROVIDER_LABELS[selected] ?? selected) : '--'
  const gcpAUp = components.ollama_gcp_a?.status === 'up'
  const gcpBUp = components.ollama_gcp_b?.status === 'up'
  const local = components.ollama_local
  const localDown = local?.status === 'down' || local?.status === 'degraded'
  const localCooling = Boolean(local?.is_cooldown)

  if (aggregate?.status === 'up' && localDown && (gcpAUp || gcpBUp)) {
    return {
      tone: 'warning',
      title: t('aiModelSummary.localFallbackDownTitle', { provider: selectedLabel }),
      detail: localCooling
        ? t('aiModelSummary.localFallbackCooldownDetail')
        : t('aiModelSummary.localFallbackDownDetail'),
    }
  }

  if (aggregate?.status === 'up') {
    return {
      tone: 'healthy',
      title: t('aiModelSummary.healthyTitle', { provider: selectedLabel }),
      detail: t('aiModelSummary.healthyDetail'),
    }
  }

  if (aggregate?.status === 'degraded') {
    return {
      tone: 'warning',
      title: t('aiModelSummary.degradedTitle', { provider: selectedLabel }),
      detail: t('aiModelSummary.degradedDetail'),
    }
  }

  if (aggregate?.status === 'down') {
    return {
      tone: 'critical',
      title: t('aiModelSummary.downTitle'),
      detail: t('aiModelSummary.downDetail'),
    }
  }

  return {
    tone: 'unknown',
    title: t('aiModelSummary.unknownTitle'),
    detail: t('aiModelSummary.unknownDetail'),
  }
}

export function AIModelStatus() {
  const t = useTranslations('dashboard')
  const [models, setModels] = useState<ModelInfo[]>([
    { name: 'GCP-A', role: 'primary', status: 'unknown' },
    { name: 'GCP-B', role: 'backup', status: 'unknown' },
    { name: '111', role: 'local', status: 'unknown' },
    { name: 'OpenClaw', role: 'agent', status: 'unknown' },
  ])
  const [summary, setSummary] = useState<RouteSummary>({
    tone: 'unknown',
    title: t('aiModelSummary.unknownTitle'),
    detail: t('aiModelSummary.unknownDetail'),
  })

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/health`)
      .then(r => r.ok ? r.json() : null)
      .then((d: HealthResponse | null) => {
        if (!d?.components) return
        setSummary(buildRouteSummary(d.components, t))
        const routeOrder = d.ollama_route_order?.length
          ? d.ollama_route_order
          : ['ollama_gcp_a', 'ollama_gcp_b', 'ollama_local']
        const providerKeys = [...routeOrder, 'openclaw']
        setModels(providerKeys.map(key => ({
          name: PROVIDER_LABELS[key] ?? key,
          role: PROVIDER_ROLES[key] ?? 'provider',
          status: d.components?.[key]?.status ?? 'unknown',
          latencyMs: d.components?.[key]?.latency_ms,
          diagnosisCode: d.components?.[key]?.diagnosis_code,
          retryAfterSeconds: d.components?.[key]?.retry_after_seconds,
          isCooldown: d.components?.[key]?.is_cooldown,
        })))
      })
      .catch(() => {})
  }, [t])

  const summaryStyle = summaryToneStyle(summary.tone)

  return (
    <div style={{
      background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10,
      overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)', flexShrink: 0,
    }}>
      <div style={{
        padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4',
        display: 'flex', alignItems: 'center', gap: 8, background: '#faf9f3',
      }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757' }} />
        <span style={{ fontSize: 14, fontWeight: 700, color: '#141413' }}>{t('aiModelStatus')}</span>
      </div>
      <div style={{
        margin: '12px 14px 0',
        border: `0.5px solid ${summaryStyle.border}`,
        background: summaryStyle.background,
        borderRadius: 6,
        padding: '8px 10px',
      }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: '#141413', lineHeight: 1.35 }}>
          {summary.title}
        </div>
        <div style={{ marginTop: 3, fontSize: 11, color: summaryStyle.color, lineHeight: 1.45 }}>
          {summary.detail}
        </div>
      </div>
      <div style={{ padding: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        {models.map(m => (
          <div key={m.name} style={{
            border: '0.5px solid #e0ddd4', borderRadius: 6, padding: '6px 8px',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: statusColor(m.status), flexShrink: 0 }} />
            <span style={{ fontSize: 12, fontWeight: 500, color: '#141413' }}>{m.name}</span>
            <span style={{ fontSize: 10, color: '#87867f', marginLeft: 'auto' }}>
              {modelDetail(m, t)}
            </span>
          </div>
        ))}
      </div>
    </div>
  )
}
