import { GlassSurface, StatusBadge } from "@nodedc/ui-react";
import type { ReactNode } from "react";

import {
  backendLabel,
  backendTone,
  eventStatusLabel,
  formatNumber,
  pipelineLatency,
} from "../presentation";
import { isConfirmedLiveState } from "../lifecycle";
import type { XgridsK1Controller } from "../runtimeContext";

function DetailRow({ label, children }: { label: string; children: ReactNode }) {
  return <div className="detail-row"><dt>{label}</dt><dd>{children}</dd></div>;
}

function LatencyTrace({ values }: { values: number[] }) {
  const ceiling = Math.max(16, ...values);
  return (
    <div className="latency-trace" aria-label="Последние измерения времени до публикации">
      {values.length ? values.map((value, index) => (
        <span key={`${index}-${value}`} style={{ height: `${Math.max(8, Math.min(100, (value / ceiling) * 100))}%` }} title={`${value.toFixed(1)} мс`} />
      )) : <p>Измерений пока нет. График появится после получения реальных данных.</p>}
    </div>
  );
}

export function K1Diagnostics({ controller, sourceLabel }: {
  controller: XgridsK1Controller;
  sourceLabel: string;
}) {
  const { state, backendStatus, eventStatus, latencyHistory } = controller;
  const streamActive = isConfirmedLiveState(state) || state?.source_mode === "replay";
  const latency = pipelineLatency(streamActive ? state?.metrics : undefined);
  return (
    <div className="diagnostics-grid">
      <GlassSurface className="status-panel" padding="lg">
        <header className="panel-heading panel-heading--compact">
          <div><span className="section-eyebrow">ТЕКУЩЕЕ СОСТОЯНИЕ</span><h2>Локальный контур</h2></div>
          <StatusBadge tone={backendTone(backendStatus)}>{backendLabel(backendStatus)}</StatusBadge>
        </header>
        <dl className="detail-list">
          <DetailRow label="Канал событий"><span className="inline-state" data-state={eventStatus}>{eventStatusLabel(eventStatus)}</span></DetailRow>
          <DetailRow label="Источник">{sourceLabel}</DetailRow>
          <DetailRow label="Адрес устройства"><code>{state?.k1_ip || "Не получен"}</code></DetailRow>
        </dl>
      </GlassSurface>
      <GlassSurface className="latency-panel" padding="lg">
        <header className="panel-heading panel-heading--compact">
          <div><span className="section-eyebrow">ПОСЛЕДНИЕ ИЗМЕРЕНИЯ</span><h2>Время до публикации</h2></div>
          <strong className="latency-now">{formatNumber(latency)} <span>мс</span></strong>
        </header>
        <LatencyTrace values={latencyHistory} />
        <div className="latency-legend"><span>Старые</span><span>Последние</span></div>
      </GlassSurface>
    </div>
  );
}
