'use client'

/**
 * AppsPanel — 應用服務狀態面板 (不含 AppLayout)
 * ================================================
 * Sprint 5: 從 /apps/page.tsx 抽取
 * 供原始頁面和整合頁面 (/observability) 共用
 *
 * 建立時間: 2026-04-09 (台北時區)
 */

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

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

interface HostService {
  name: string
  status: string
  port: number | null
  latency_ms: number | null
}

interface Host {
  ip: string
  name: string
  status: string
  services: HostService[]
}

const STATUS_COLOR: Record<string, string> = {
  up: '#22C55E',
  healthy: '#22C55E',
  down: '#cc2200',
  degraded: '#F59E0B',
  unreachable: '#87867f',
}

export function AppsPanel() {
  const t = useTranslations('apps')
  const [hosts, setHosts] = useState<Host[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/dashboard`)
      .then(r => r.json())
      .then(data => { setHosts(data.hosts ?? []); setLoading(false) })
      .catch(err => { setError(String(err)); setLoading(false) })
  }, [])

  const allServices = hosts.flatMap(h =>
    h.services.map(s => ({ ...s, hostName: h.name, hostIp: h.ip }))
  )

  return (
    <div style={{ padding: '24px', background: '#f5f4ed', minHeight: '100%' }}>
      <div style={{ marginBottom: '20px' }}>
        <h1 style={{ fontSize: 18, fontWeight: 700, color: '#141413', margin: 0, fontFamily: 'var(--font-body), monospace' }}>{t('title')}</h1>
        <p style={{ fontSize: 12, color: '#87867f', margin: '4px 0 0', fontFamily: 'var(--font-body), monospace' }}>{t('subtitle')}</p>
      </div>
      <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 700, padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4', background: '#faf9f3', fontFamily: 'var(--font-body), monospace', color: '#141413' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#22C55E', display: 'inline-block' }} />
          {t('title')} ({loading ? '...' : allServices.length})
        </div>
        {loading ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('loading')}</div>
        ) : error ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#cc2200', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('error')}</div>
        ) : allServices.length === 0 ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('noApps')}</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>
            <thead>
              <tr style={{ background: '#faf9f3' }}>
                {[t('service'), t('host'), t('port'), t('latency'), t('status')].map(col => (
                  <th key={col} style={{ padding: '8px 14px', textAlign: 'left', fontWeight: 600, color: '#87867f', borderBottom: '0.5px solid #e0ddd4', fontSize: 11 }}>{col}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {allServices.map((s, i) => (
                <tr key={i} style={{ borderBottom: '0.5px solid #f0ede4' }}>
                  <td style={{ padding: '8px 14px', fontWeight: 500, color: '#141413' }}>{s.name}</td>
                  <td style={{ padding: '8px 14px', color: '#87867f', fontSize: 12 }}>{s.hostName} <span style={{ color: '#c0bdb4' }}>({s.hostIp})</span></td>
                  <td style={{ padding: '8px 14px', color: '#87867f' }}>{s.port ?? '—'}</td>
                  <td style={{ padding: '8px 14px', color: '#87867f' }}>{s.latency_ms != null ? `${s.latency_ms.toFixed(0)}ms` : '—'}</td>
                  <td style={{ padding: '8px 14px' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600, textTransform: 'uppercase', color: STATUS_COLOR[s.status] ?? '#87867f' }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: STATUS_COLOR[s.status] ?? '#87867f', display: 'inline-block' }} />
                      {s.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
