'use client';

import { useEffect, useState } from 'react';
import { useSuperAdmin } from '../_lib/super-admin-context';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function AdminDashboard() {
  const { admin, loading } = useSuperAdmin();
  const router = useRouter();
  const [tenants, setTenants] = useState<any[]>([]);
  const [bots, setBots] = useState<any[]>([]);

  useEffect(() => {
    if (loading) return;
    if (!admin) { router.replace('/admin/login'); return; }
    fetch('/api/admin/tenants').then(r => r.ok && r.json()).then(d => setTenants(d ?? [])).catch(() => {});
    fetch('/api/admin/bots').then(r => r.ok && r.json()).then(d => setBots(d ?? [])).catch(() => {});
  }, [admin, loading, router]);

  if (loading) return <p className="text-gray-500">Loading...</p>;
  if (!admin) return null;

  const totalTenants = tenants.length;
  const activeTenants = tenants.filter((t: any) => t.isActive).length;
  const totalBots = bots.length;
  const totalMessages = tenants.reduce((s: number, t: any) => s + (t.stats?.messages ?? 0), 0);

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">Admin Dashboard</h1>
      <div className="grid grid-cols-4 gap-4 mb-8">
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Tenants</div>
          <div className="text-2xl font-bold mt-1">{totalTenants}</div>
          <div className="text-xs text-gray-400">{activeTenants} active</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Bot Accounts</div>
          <div className="text-2xl font-bold mt-1">{totalBots}</div>
          <div className="text-xs text-gray-400">in pool</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Messages</div>
          <div className="text-2xl font-bold mt-1">{totalMessages}</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Avg tenants/bot</div>
          <div className="text-2xl font-bold mt-1">{totalBots ? Math.round(totalTenants / totalBots) : 0}</div>
        </div>
      </div>
      <div className="flex gap-4">
        <Link href="/admin/tenants" className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm">Manage Tenants</Link>
        <Link href="/admin/bots" className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm">Manage Bots</Link>
      </div>
    </div>
  );
}
