// components/StatsBar.tsx
"use client";

import { useEffect, useState, useCallback } from "react";
import { Globe, Inbox, TimerReset, Loader2 } from "lucide-react";

interface Stats {
  activeDomains: number;
  activeEmails: number;
  expiringToday: number;
}

export default function StatsBar() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch("/api/stats");
      if (!res.ok) throw new Error("Failed to load stats");
      const data = await res.json();
      setStats(data);
      setError(null);
    } catch {
      setError("Unable to load stats");
    }
  }, []);

  useEffect(() => {
    fetchStats();
    // Real-time-ish refresh every 30 seconds
    const interval = setInterval(fetchStats, 30_000);
    return () => clearInterval(interval);
  }, [fetchStats]);

  const cards = [
    {
      label: "Active Domains",
      value: stats?.activeDomains,
      icon: Globe,
      accent: "text-emerald-400 bg-emerald-950/40",
    },
    {
      label: "Active Emails",
      value: stats?.activeEmails,
      icon: Inbox,
      accent: "text-indigo-400 bg-indigo-950/40",
    },
    {
      label: "Expiring Today",
      value: stats?.expiringToday,
      icon: TimerReset,
      accent: "text-amber-400 bg-amber-950/40",
    },
  ];

  return (
    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
      {cards.map(({ label, value, icon: Icon, accent }) => (
        <div
          key={label}
          className="bg-slate-900 border border-slate-800 rounded-xl p-4 flex items-center gap-4"
        >
          <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${accent}`}>
            <Icon className="w-5 h-5" />
          </div>
          <div>
            <p className="text-xs text-slate-400">{label}</p>
            <p className="text-2xl font-semibold text-white leading-tight">
              {error ? (
                "—"
              ) : value === undefined ? (
                <Loader2 className="w-4 h-4 animate-spin text-slate-500" />
              ) : (
                value
              )}
            </p>
          </div>
        </div>
      ))}
    </div>
  );
}
