'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { Users, Crown, Radio, CalendarDays, Trophy, FileCheck2, Wallet, ArrowUpRight, UserRound, CreditCard, Clock3 } from 'lucide-react';
import { apiRequest } from '../../lib/api';
import { Badge } from '../../components/Badge';

const money = (n: number) => `₹${Number(n || 0).toLocaleString('en-IN')}`;

export default function AdminDashboardPage() {
  const [stats, setStats] = useState<any>(null);
  const [matches, setMatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const [statsRes, matchesRes] = await Promise.all([apiRequest('/dashboard/stats'), apiRequest('/matches?publicationStatus=PUBLISHED')]);
        setStats(statsRes.data);
        setMatches(matchesRes.data || []);
      } catch (e) { console.error(e); }
      finally { setLoading(false); }
    })();
  }, []);

  const cards: Array<{
    label: string;
    value: number;
    Icon: React.ComponentType<{ className?: string }>;
    sub: string;
    color: string;
  }> = [
    { label: 'Total Users', value: stats?.customers ?? 0, Icon: Users, sub: 'registered customers', color: 'text-red-400' },
    { label: 'Premium Users', value: stats?.premiumUsers ?? 0, Icon: Crown, sub: 'active memberships', color: 'text-amber-400' },
    { label: 'Upcoming Matches', value: stats?.matches?.upcoming ?? 0, Icon: CalendarDays, sub: 'scheduled fixtures', color: 'text-cyan-400' },
    { label: 'Live Matches', value: stats?.matches?.live ?? 0, Icon: Radio, sub: 'currently live', color: 'text-emerald-400' },
    { label: 'Active Contests', value: stats?.contests ?? 0, Icon: Trophy, sub: 'open contests', color: 'text-violet-400' },
    { label: 'Completed Matches', value: stats?.matches?.completed ?? 0, Icon: Clock3, sub: 'completed fixtures', color: 'text-zinc-300' },
    { label: 'Pending KYC', value: stats?.pendingKyc ?? 0, Icon: FileCheck2, sub: 'needs review', color: 'text-orange-400' },
    { label: 'Pending Withdrawals', value: stats?.pendingWithdrawals ?? 0, Icon: CreditCard, sub: 'needs review', color: 'text-rose-400' },
  ];

  if (loading) return <div className="admin-page"><div className="admin-panel h-48 animate-pulse" /></div>;

  return (
    <div className="admin-page space-y-7">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <div className="admin-kicker">MY11s Control Center</div>
          <h1 className="admin-title">Platform Dashboard</h1>
          <p className="admin-subtitle">Real-time operational overview · current build is an admin-panel work in progress.</p>
        </div>
        <div className="flex gap-2">
          <Link href="/admin/matches" className="admin-action red"><CalendarDays className="h-3.5 w-3.5" /> New Match</Link>
          <Link href="/admin/players" className="admin-action"><UserRound className="h-3.5 w-3.5" /> Add Player</Link>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
        {cards.map(({ label, value, Icon, sub, color }) => (
          <div className="admin-stat" key={String(label)}>
            <div className="relative z-10 flex items-start justify-between">
              <div>
                <div className="text-[9px] font-extrabold uppercase tracking-[.14em] text-zinc-500">{label}</div>
                <div className="mt-2 text-2xl font-black tracking-tight text-white">{String(value)}</div>
                <div className="mt-1 text-[10px] text-zinc-600">{sub}</div>
              </div>
              <Icon className={`h-5 w-5 ${color}`} />
            </div>
          </div>
        ))}
      </div>

      <div className="grid gap-5 xl:grid-cols-[1.55fr_.9fr]">
        <section className="admin-panel overflow-hidden">
          <div className="flex items-center justify-between border-b border-white/5 px-5 py-4">
            <div><div className="text-sm font-extrabold text-white">Published Fixtures</div><div className="mt-1 text-[10px] text-zinc-600">Upcoming and live matches visible to operations.</div></div>
            <Link href="/admin/matches" className="text-[10px] font-bold text-red-400 hover:text-red-300">Manage all →</Link>
          </div>
          <div className="overflow-x-auto">
            <table className="admin-table min-w-[720px]">
              <thead><tr><th>Match</th><th>Format</th><th>Venue</th><th>Start</th><th>Status</th><th>Scorer</th></tr></thead>
              <tbody>
                {matches.slice(0, 8).map((m) => <tr key={m._id}>
                  <td><div className="font-bold text-white">{m.teamA?.shortName} <span className="text-zinc-600">vs</span> {m.teamB?.shortName}</div><div className="mt-0.5 text-[9px] text-zinc-600">{m.title}</div></td>
                  <td className="font-mono">{m.format} · {m.totalOvers} ov</td>
                  <td>{m.venue}</td>
                  <td className="font-mono text-zinc-300">{new Date(m.startTime).toLocaleString('en-IN',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'})}</td>
                  <td><Badge variant={m.status === 'LIVE' ? 'live' : m.status === 'COMPLETED' ? 'slate' : 'amber'}>{m.status}</Badge></td>
                  <td>{m.assignedScorerId?.name || <span className="text-zinc-600">Unassigned</span>}</td>
                </tr>)}
              </tbody>
            </table>
            {!matches.length && <div className="p-10 text-center text-xs text-zinc-600">No published matches yet.</div>}
          </div>
        </section>

        <section className="space-y-5">
          <div className="admin-panel p-5">
            <div className="flex items-center justify-between"><div><div className="text-sm font-extrabold text-white">Wallet Snapshot</div><div className="mt-1 text-[10px] text-zinc-600">All user balances · INR</div></div><Wallet className="h-5 w-5 text-emerald-400" /></div>
            <div className="mt-5 space-y-3">
              <div className="flex justify-between text-xs"><span className="text-zinc-500">Deposit Balance</span><b className="text-white">{money(stats?.wallet?.totalDeposit)}</b></div>
              <div className="flex justify-between text-xs"><span className="text-zinc-500">Winning Balance</span><b className="text-white">{money(stats?.wallet?.totalWinning)}</b></div>
              <div className="flex justify-between text-xs"><span className="text-zinc-500">Bonus Balance</span><b className="text-white">{money(stats?.wallet?.totalBonus)}</b></div>
              <div className="mt-4 border-t border-white/5 pt-4 flex justify-between"><span className="text-[10px] font-extrabold uppercase tracking-widest text-zinc-500">Total Balance</span><b className="text-lg text-emerald-400">{money(stats?.wallet?.totalVolume)}</b></div>
            </div>
          </div>
          <div className="admin-panel p-5">
            <div className="flex items-center justify-between"><div><div className="text-sm font-extrabold text-white">Recent Activity</div><div className="mt-1 text-[10px] text-zinc-600">Latest administrative events</div></div><ArrowUpRight className="h-4 w-4 text-zinc-600" /></div>
            <div className="mt-4 space-y-2">
              {(stats?.recentAudit || []).slice(0,5).map((log:any) => <div key={log._id} className="flex items-center justify-between rounded-xl border border-white/5 bg-black/15 px-3 py-2.5"><div className="min-w-0"><div className="truncate text-[11px] font-bold text-zinc-200">{log.action}</div><div className="text-[9px] text-zinc-600">{log.module || 'SYSTEM'}</div></div><span className="text-[9px] text-zinc-600">{new Date(log.createdAt).toLocaleTimeString('en-IN',{hour:'2-digit',minute:'2-digit'})}</span></div>)}
              {!stats?.recentAudit?.length && <div className="py-4 text-center text-xs text-zinc-600">No recent activity.</div>}
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}
