import { useLiveStreamStore } from "../../../features/liveStream/model/liveStream.store";
import { WsStatusBadge } from "../../../features/liveStream/ui/WsStatusBadge";
import { AudioMeter } from "./AudioMeter";
import { FrequencyHistoryChart } from "./FrequencyHistoryChart";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../../../shared/ui/card";
import { freqToNote } from "../../../entities/audioSample/lib/note";
import { formatTimeHHMMSS, isStale } from "../../../shared/lib/time";

export function AudioLiveWidget() {
  const status = useLiveStreamStore((s) => s.status);
  const latest = useLiveStreamStore((s) => s.latest);
  const history60s = useLiveStreamStore((s) => s.history60s);
  const peakHoldDb3s = useLiveStreamStore((s) => s.peakHoldDb3s);
  const lastMessageAt = useLiveStreamStore((s) => s.lastMessageAt);

  const stale = isStale(lastMessageAt, 1500);

  const note = latest ? freqToNote(latest.freq_hz) : "--";

  return (
    <div className="grid gap-4 lg:grid-cols-3">
      <div className="lg:col-span-1">
        <AudioMeter
          rmsDb={latest?.rms_db ?? null}
          peakHoldDb3s={peakHoldDb3s}
        />
      </div>

      <div className="lg:col-span-2 grid gap-4">
        <Card>
          <CardHeader className="pb-2 flex flex-row items-center justify-between gap-3">
            <CardTitle className="text-base">Live status</CardTitle>
            <WsStatusBadge status={status} />
          </CardHeader>
          <CardContent className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <div className="text-sm text-muted-foreground">Last update</div>
              <div className="text-lg font-medium tabular-nums">
                {lastMessageAt ? formatTimeHHMMSS(lastMessageAt) : "—"}
                <span
                  className={`ml-2 text-xs ${stale ? "text-rose-600" : "text-emerald-600"}`}
                >
                  {stale ? "stale" : "ok"}
                </span>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground">Frequency</div>
              <div className="text-lg font-medium tabular-nums">
                {latest ? `${latest.freq_hz.toFixed(0)} Hz` : "—"}{" "}
                <span className="text-muted-foreground">({note})</span>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground">RMS</div>
              <div className="text-lg font-medium tabular-nums">
                {latest ? `${latest.rms_db.toFixed(1)} dB` : "—"}
              </div>
            </div>
          </CardContent>
        </Card>

        <FrequencyHistoryChart history={history60s} />
      </div>
    </div>
  );
}
