"use client";

import { useEffect, useState, useCallback } from "react";

interface Stats {
  activeUsers: number;
  messagesToday: number;
  creditsPurchasedToday: number;
  activeLivecamStreams: number;
  moderationQueueSize: number;
  newUsersToday: number;
  revenueToday: number;
}

export default function CommandCenterPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/command-center");
      if (res.ok) {
        const data = await res.json();
        setStats(data.data);
        setLastUpdated(new Date());
        setError(null);
      } else {
        setError("Failed to fetch stats");
      }
    } catch {
      setError("Network error");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 30_000); // Auto-refresh every 30s
    return () => clearInterval(interval);
  }, [fetchStats]);

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-8 w-64 bg-surface-light rounded animate-pulse" />
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {Array.from({ length: 7 }).map((_, i) => (
            <div key={i} className="bg-surface rounded-xl p-6 animate-pulse">
              <div className="h-4 w-20 bg-surface-light rounded mb-3" />
              <div className="h-8 w-16 bg-surface-light rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  const cards = stats
    ? [
        {
          label: "Active Users Now",
          value: stats.activeUsers,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          ),
          color: "text-green-400",
          bgColor: "bg-green-500/10",
          pulse: true,
        },
        {
          label: "Messages Today",
          value: stats.messagesToday,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
          ),
          color: "text-blue-400",
          bgColor: "bg-blue-500/10",
        },
        {
          label: "Credits Purchased Today",
          value: stats.creditsPurchasedToday,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
            </svg>
          ),
          color: "text-gold",
          bgColor: "bg-gold/10",
        },
        {
          label: "Active Livecam Streams",
          value: stats.activeLivecamStreams,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          ),
          color: "text-red-400",
          bgColor: "bg-red-500/10",
          pulse: stats.activeLivecamStreams > 0,
        },
        {
          label: "Moderation Queue",
          value: stats.moderationQueueSize,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          ),
          color: stats.moderationQueueSize > 10 ? "text-orange-400" : "text-text-muted",
          bgColor: stats.moderationQueueSize > 10 ? "bg-orange-500/10" : "bg-surface-light",
        },
        {
          label: "New Users Today",
          value: stats.newUsersToday,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
            </svg>
          ),
          color: "text-purple-400",
          bgColor: "bg-purple-500/10",
        },
        {
          label: "Revenue Today",
          value: `${stats.revenueToday.toFixed(0)}`,
          icon: (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
            </svg>
          ),
          color: "text-emerald-400",
          bgColor: "bg-emerald-500/10",
        },
      ]
    : [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Real-Time Command Center</h1>
          <p className="text-text-muted text-sm mt-1">
            Live platform metrics, auto-refreshes every 30 seconds.
          </p>
        </div>
        <div className="flex items-center gap-3">
          {error && <span className="text-xs text-red-400">{error}</span>}
          {lastUpdated && (
            <span className="text-xs text-text-muted">
              Updated {lastUpdated.toLocaleTimeString()}
            </span>
          )}
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" title="Live" />
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {cards.map((card, i) => (
          <div
            key={i}
            className="bg-surface rounded-xl p-5 border border-white/5 hover:border-white/10 transition-colors"
          >
            <div className="flex items-center gap-3 mb-3">
              <div className={`w-10 h-10 rounded-lg ${card.bgColor} flex items-center justify-center ${card.color}`}>
                {card.icon}
              </div>
            </div>
            <p className="text-xs text-text-muted uppercase tracking-wider mb-1">{card.label}</p>
            <p className={`text-2xl font-bold ${card.color} flex items-center gap-2`}>
              {card.value}
              {card.pulse && (
                <span className="w-2 h-2 bg-current rounded-full animate-pulse" />
              )}
            </p>
          </div>
        ))}
      </div>

      {/* Quick actions */}
      <div className="bg-surface rounded-xl p-6 border border-white/5">
        <h2 className="text-lg font-semibold mb-4">Quick Actions</h2>
        <div className="flex flex-wrap gap-3">
          <a
            href="/admin/moderation"
            className="px-4 py-2 rounded-lg bg-surface-light border border-white/5 text-sm text-text hover:border-primary/30 transition-colors"
          >
            Moderation Queue
          </a>
          <a
            href="/admin/users"
            className="px-4 py-2 rounded-lg bg-surface-light border border-white/5 text-sm text-text hover:border-primary/30 transition-colors"
          >
            Manage Users
          </a>
          <a
            href="/admin/churn"
            className="px-4 py-2 rounded-lg bg-surface-light border border-white/5 text-sm text-text hover:border-primary/30 transition-colors"
          >
            Churn Dashboard
          </a>
          <a
            href="/admin/finance"
            className="px-4 py-2 rounded-lg bg-surface-light border border-white/5 text-sm text-text hover:border-primary/30 transition-colors"
          >
            Finance
          </a>
          <a
            href="/admin/reports"
            className="px-4 py-2 rounded-lg bg-surface-light border border-white/5 text-sm text-text hover:border-primary/30 transition-colors"
          >
            Reports
          </a>
        </div>
      </div>
    </div>
  );
}
