/**
 * Compact admin widget that shows three live numbers, updating every
 * 30 seconds while the admin sits on the page:
 *
 *   ┌─ Live now    ┐  ┌─ Total installs ┐  ┌─ Active 24h ┐
 *   │     142      │  │     12,438      │  │   3,521     │
 *   └──────────────┘  └─────────────────┘  └─────────────┘
 *
 * Data sources:
 *   • /api/admin/stats/live      (heartbeats from the last 90 s)
 *   • /api/admin/stats/installs  (fcm_tokens + DAU/WAU windows)
 */
import { useEffect, useState } from "react";
import { Activity, Smartphone, TrendingUp, RefreshCw } from "lucide-react";
import {
  apiAdminInstallStats,
  apiAdminLiveStats,
  type InstallStats,
  type LiveStats,
} from "@/lib/nadiAuth";

const LiveStatsCard = () => {
  const [live, setLive] = useState<LiveStats | null>(null);
  const [installs, setInstalls] = useState<InstallStats | null>(null);
  const [loading, setLoading] = useState(false);

  const refresh = async () => {
    setLoading(true);
    try {
      const [l, i] = await Promise.all([
        apiAdminLiveStats().catch(() => null),
        apiAdminInstallStats().catch(() => null),
      ]);
      if (l) setLive(l);
      if (i) setInstalls(i);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void refresh();
    const id = window.setInterval(refresh, 30_000);
    return () => window.clearInterval(id);
  }, []);

  return (
    <div
      className="glass-card rounded-2xl p-4 sm:p-5"
      data-testid="live-stats-card"
    >
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <Activity className="w-4 h-4 text-primary" />
          <h3 className="text-foreground/90 text-sm tracking-wide">
            Engagement
          </h3>
        </div>
        <button
          onClick={() => { if (!loading) refresh(); }}
          aria-busy={loading || undefined}
          data-loading={loading || undefined}
          data-testid="live-stats-refresh"
          className={`w-7 h-7 rounded-full glass flex items-center justify-center hover:border-primary/40 ${loading ? "opacity-50 pointer-events-none" : ""}`}
        >
          <RefreshCw
            className={`w-3.5 h-3.5 text-muted-foreground ${loading ? "animate-spin" : ""}`}
          />
        </button>
      </div>

      <div className="grid grid-cols-3 gap-2 sm:gap-3">
        <Stat
          icon={Activity}
          label="Live now"
          value={live?.live_watchers ?? 0}
          accent
          testId="stat-live"
        />
        <Stat
          icon={Smartphone}
          label="Installs"
          value={installs?.total_installs ?? 0}
          testId="stat-installs"
        />
        <Stat
          icon={TrendingUp}
          label="Active 24h"
          value={installs?.dau ?? 0}
          testId="stat-dau"
        />
      </div>

      {live && live.top_channels.length > 0 && (
        <div className="mt-3 pt-3 border-t border-border/40">
          <p className="text-[10px] uppercase tracking-wider text-muted-foreground mb-1.5">
            Top channels right now
          </p>
          <ul className="space-y-1">
            {live.top_channels.slice(0, 3).map((c) => (
              <li
                key={c.channel}
                className="flex items-center justify-between text-[11px]"
              >
                <span className="truncate text-foreground/80">{c.channel}</span>
                <span className="text-primary tabular-nums shrink-0 ml-2">
                  {c.viewers}
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}

      {installs && (
        <div className="mt-3 pt-3 border-t border-border/40 space-y-1.5" data-testid="install-breakdown">
          <p className="text-[10px] uppercase tracking-wider text-muted-foreground">
            Install sources
          </p>
          <div className="grid grid-cols-2 gap-2 text-[11px]">
            <div className="glass rounded-lg px-2.5 py-2" data-testid="stat-install-trial-devices">
              <p className="text-muted-foreground">Trial devices</p>
              <p className="text-foreground tabular-nums font-medium">
                {(installs.total_installs_trial_devices ?? 0).toLocaleString()}
              </p>
            </div>
            <div className="glass rounded-lg px-2.5 py-2" data-testid="stat-install-fcm-devices">
              <p className="text-muted-foreground">Push tokens</p>
              <p className="text-foreground tabular-nums font-medium">
                {(installs.total_installs_fcm_tokens ?? 0).toLocaleString()}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const Stat = ({
  icon: Icon,
  label,
  value,
  accent,
  testId,
}: {
  icon: typeof Activity;
  label: string;
  value: number;
  accent?: boolean;
  testId: string;
}) => (
  <div
    className={`rounded-xl p-3 flex flex-col gap-0.5 ${accent ? "bg-primary/10 border border-primary/30" : "glass"}`}
    data-testid={testId}
  >
    <div className="flex items-center gap-1.5">
      <Icon
        className={`w-3 h-3 ${accent ? "text-primary" : "text-muted-foreground"}`}
      />
      <span
        className={`text-[10px] uppercase tracking-wider ${accent ? "text-primary" : "text-muted-foreground"}`}
      >
        {label}
      </span>
    </div>
    <span
      className={`text-xl sm:text-2xl font-display tabular-nums ${accent ? "gold-text" : "text-foreground"}`}
    >
      {value.toLocaleString()}
    </span>
  </div>
);

export default LiveStatsCard;
