'use client';
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Users, Receipt, IndianRupee, Crown, Shield } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';

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

  useEffect(() => {
    fetch('/api/admin/stats').then(r => r.json()).then(d => { setStats(d); setLoading(false); }).catch(() => setLoading(false));
  }, []);

  const cards = [
    { label: 'Total Users', value: stats?.totalUsers ?? 0, icon: Users, color: 'text-blue-500', bg: 'bg-blue-500/10' },
    { label: 'Active Subscriptions', value: stats?.activeSubscriptions ?? 0, icon: Crown, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
    { label: 'Total Invoices', value: stats?.totalInvoices ?? 0, icon: Receipt, color: 'text-amber-500', bg: 'bg-amber-500/10' },
    { label: 'Total Revenue', value: `₹${(stats?.totalRevenue ?? 0)?.toLocaleString?.('en-IN') ?? '0'}`, icon: IndianRupee, color: 'text-primary', bg: 'bg-primary/10' },
  ];

  return (
    <div className="max-w-[1200px] mx-auto">
      <div className="mb-8">
        <h1 className="font-display text-2xl font-bold tracking-tight flex items-center gap-2"><Shield className="w-6 h-6 text-primary" /> Admin Dashboard</h1>
        <p className="text-muted-foreground text-sm mt-1">System overview and management</p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {cards.map((s: any, i: number) => (
          <motion.div key={i} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.1 }}>
            <Card>
              <CardContent className="p-5">
                <div className={`w-10 h-10 rounded-lg ${s?.bg ?? ''} flex items-center justify-center mb-3`}>
                  <s.icon className={`w-5 h-5 ${s?.color ?? ''}`} />
                </div>
                <p className="text-2xl font-bold font-mono">{loading ? '...' : s?.value ?? 0}</p>
                <p className="text-xs text-muted-foreground mt-1">{s?.label ?? ''}</p>
              </CardContent>
            </Card>
          </motion.div>
        ))}
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader><CardTitle className="text-base">Recent Users</CardTitle></CardHeader>
          <CardContent>
            {loading ? <div className="space-y-2">{[1,2,3].map(i => <div key={i} className="h-12 bg-muted rounded animate-pulse" />)}</div> : (
              <div className="space-y-2">
                {(stats?.recentUsers ?? []).map((u: any) => (
                  <div key={u?.id} className="flex items-center justify-between p-3 rounded-lg hover:bg-muted">
                    <div>
                      <p className="text-sm font-medium">{u?.name ?? ''}</p>
                      <p className="text-xs text-muted-foreground">{u?.email ?? ''}</p>
                    </div>
                    <div className="flex gap-2">
                      <Badge variant="secondary" className={u?.subscriptionStatus === 'ACTIVE' ? 'bg-green-100 text-green-700' : ''}>{u?.subscriptionStatus ?? ''}</Badge>
                      {u?.role === 'ADMIN' && <Badge>Admin</Badge>}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader><CardTitle className="text-base">Recent Invoices</CardTitle></CardHeader>
          <CardContent>
            {loading ? <div className="space-y-2">{[1,2,3].map(i => <div key={i} className="h-12 bg-muted rounded animate-pulse" />)}</div> : (
              <div className="space-y-2">
                {(stats?.recentInvoices ?? []).map((inv: any) => (
                  <div key={inv?.id} className="flex items-center justify-between p-3 rounded-lg hover:bg-muted">
                    <div>
                      <p className="text-sm font-medium">{inv?.invoiceNumber ?? ''}</p>
                      <p className="text-xs text-muted-foreground">{inv?.user?.name ?? ''} → {inv?.customer?.name ?? ''}</p>
                    </div>
                    <p className="text-sm font-mono font-semibold">₹{(inv?.totalAmount ?? 0)?.toLocaleString?.('en-IN') ?? '0'}</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
