/*
 * W12 시스템관리 — 시스템 상태 대시보드.
 * 정본: GET /api/admin/system-health → SystemHealth (SystemHealthController). DB/Redis/워커/디스크/메모리/가동시간.
 * 보안: 내부IP·스택트레이스 미노출(백엔드 집계값만).
 */
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { ErrorState, Skeleton } from '../../components/ui/States';
import { Button } from '../../components/ui/Button';
import { systemHealthApi, type SystemHealth } from './systemBasicsApi';
import './admin-modules.css';

export function SystemHealthPage() {
  const { t } = useTranslation();
  const q = useQuery({
    queryKey: ['admin-system-health'],
    queryFn: systemHealthApi.get,
    retry: false,
    refetchInterval: 15000,
  });
  const h = q.data;

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('sysHealth.title')}</h1>
          <p className="kx-adm__subtitle">{t('sysHealth.subtitle')}</p>
        </div>
        <Button variant="ghost" onClick={() => q.refetch()}>{t('sysHealth.refresh')}</Button>
      </header>

      {q.isLoading && <Skeleton height={220} radius={12} />}
      {q.isError && !q.isLoading && <ErrorState message={t('sysHealth.loadError')} onRetry={() => q.refetch()} />}

      {!q.isLoading && !q.isError && h && (
        <>
          <section className="kx-adm-health-grid">
            <StatusCard label={t('sysHealth.db')} value={h.db} tone={statusTone(h.db)} />
            <StatusCard label={t('sysHealth.redis')} value={h.redis} tone={statusTone(h.redis)} />
            <StatusCard label={t('sysHealth.worker')} value={h.worker}
                        sub={t('sysHealth.queueDepth', { n: h.queueDepth < 0 ? 'N/A' : h.queueDepth })}
                        tone={statusTone(h.worker)} />
          </section>
          <section className="kx-card kx-adm-metrics">
            <Metric label={t('sysHealth.disk')} value={metricPct(h.diskFreePct)}
                    sub={t('sysHealth.diskFree', { mb: h.diskFreeMb.toLocaleString() })} />
            <Metric label={t('sysHealth.mem')} value={metricPct(h.memUsedPct)} />
            <Metric label={t('sysHealth.uptime')} value={fmtUptime(h.uptimeSec)} />
            <Metric label={t('sysHealth.version')} value={h.version} />
          </section>
        </>
      )}
    </div>
  );
}

function statusTone(v: string): 'success' | 'error' | 'neutral' {
  const s = (v ?? '').toUpperCase();
  if (s === 'UP') return 'success';
  if (s === 'DOWN') return 'error';
  return 'neutral';
}

function metricPct(n: number): string {
  return n < 0 ? 'N/A' : `${n}%`;
}

function StatusCard({ label, value, sub, tone }: {
  label: string; value: string; sub?: string; tone: 'success' | 'error' | 'neutral';
}) {
  return (
    <div className={`kx-card kx-adm-health-card kx-adm-health-card--${tone}`}>
      <span className="kx-adm-health-card__label">{label}</span>
      <span className="kx-adm-health-card__value">{value}</span>
      {sub && <span className="kx-adm-health-card__sub">{sub}</span>}
    </div>
  );
}

function Metric({ label, value, sub }: { label: string; value: string; sub?: string }) {
  return (
    <div className="kx-adm-metric">
      <span className="kx-adm-metric__label">{label}</span>
      <span className="kx-adm-metric__value tnum">{value}</span>
      {sub && <span className="kx-adm-metric__sub">{sub}</span>}
    </div>
  );
}

function fmtUptime(sec: number): string {
  if (sec < 0) return 'N/A';
  const d = Math.floor(sec / 86400);
  const h = Math.floor((sec % 86400) / 3600);
  const m = Math.floor((sec % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

export type { SystemHealth };
