import { useState, useEffect } from 'react';
import Head from 'next/head';
import Layout from '../../components/Layout';
import { adminAPI } from '../../services/api';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line } from 'recharts';

export default function AdminDashboard() {
    const [stats, setStats] = useState<any>(null);
    const [users, setUsers] = useState<any[]>([]);
    const [revenue, setRevenue] = useState<any>({});
    const [loading, setLoading] = useState(true);
    const [genForm, setGenForm] = useState({ userId: '', plan: 'PRO_MONTHLY', durationDays: 30 });

    useEffect(() => { loadAdmin(); }, []);

    const loadAdmin = async () => {
        try {
            const [dashRes, usersRes, revRes] = await Promise.all([
                adminAPI.getDashboard(),
                adminAPI.getUsers({ page: '1', limit: '20' }),
                adminAPI.getRevenue(12),
            ]);
            setStats(dashRes.data.data);
            setUsers(usersRes.data.data.users || []);
            setRevenue(revRes.data.data);
        } catch (err) { console.error(err); }
        setLoading(false);
    };

    const handleSuspend = async (id: string) => {
        if (!confirm('Suspend user ini?')) return;
        await adminAPI.suspendUser(id);
        loadAdmin();
    };

    const handleActivate = async (id: string) => {
        await adminAPI.activateUser(id);
        loadAdmin();
    };

    const handleGenerateLicense = async () => {
        if (!genForm.userId) return alert('User ID required');
        try {
            await adminAPI.generateLicense({ userId: genForm.userId, plan: genForm.plan, durationDays: genForm.durationDays });
            alert('License generated!');
            setGenForm({ userId: '', plan: 'PRO_MONTHLY', durationDays: 30 });
        } catch (err: any) { alert(err.response?.data?.message || 'Failed'); }
    };

    const formatIDR = (n: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(n);

    const revenueChart = Object.entries(revenue?.monthlyRevenue || {}).map(([month, amount]) => ({
        month,
        revenue: amount as number,
    }));

    if (loading) return <Layout requireAdmin><div className="flex justify-center py-20"><div className="animate-spin w-8 h-8 border-4 border-brand-primary border-t-transparent rounded-full" /></div></Layout>;

    return (
        <>
            <Head><title>Admin – MarketScope</title></Head>
            <Layout requireAdmin>
                <div className="animate-fade-in">
                    <h1 className="text-2xl font-bold mb-6">🛡️ Admin Dashboard</h1>

                    {/* Stats */}
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Total Users</p>
                            <p className="text-3xl font-bold text-brand-primary mt-1">{stats?.totalUsers || 0}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Active Subs</p>
                            <p className="text-3xl font-bold text-green-400 mt-1">{stats?.activeSubscriptions || 0}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Total Revenue</p>
                            <p className="text-2xl font-bold text-yellow-400 mt-1">{formatIDR(stats?.totalRevenue || 0)}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Total Scans</p>
                            <p className="text-3xl font-bold text-purple-400 mt-1">{stats?.totalScans || 0}</p>
                        </div>
                    </div>

                    {/* Revenue Chart */}
                    <div className="card mb-8">
                        <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">💰 Monthly Revenue</h3>
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={revenueChart}>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                                    <XAxis dataKey="month" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                                    <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={(v) => `${(v / 1000000).toFixed(1)}jt`} />
                                    <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#e2e8f0' }} formatter={(v: number) => formatIDR(v)} />
                                    <Bar dataKey="revenue" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        {/* Users Table */}
                        <div className="card col-span-2">
                            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">👥 Users</h3>
                            <div className="overflow-x-auto max-h-96">
                                <table className="w-full">
                                    <thead className="sticky top-0 bg-dark-card">
                                        <tr className="text-left text-xs text-gray-500 uppercase border-b border-dark-border">
                                            <th className="pb-3">Name</th>
                                            <th className="pb-3">Email</th>
                                            <th className="pb-3">Role</th>
                                            <th className="pb-3">Status</th>
                                            <th className="pb-3">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {users.map((u) => (
                                            <tr key={u.id} className="border-b border-dark-border/50 text-sm">
                                                <td className="py-2.5">{u.name}</td>
                                                <td className="py-2.5 text-gray-400">{u.email}</td>
                                                <td className="py-2.5"><span className={`text-xs px-2 py-0.5 rounded ${u.role.includes('PRO') ? 'bg-yellow-500/10 text-yellow-400' : u.role === 'ADMIN' ? 'bg-purple-500/10 text-purple-400' : 'bg-gray-500/10 text-gray-400'}`}>{u.role}</span></td>
                                                <td className="py-2.5"><span className={`text-xs ${u.status === 'ACTIVE' ? 'text-green-400' : 'text-red-400'}`}>{u.status}</span></td>
                                                <td className="py-2.5">
                                                    {u.status === 'ACTIVE' ? (
                                                        <button onClick={() => handleSuspend(u.id)} className="text-xs text-red-400 hover:underline">Suspend</button>
                                                    ) : (
                                                        <button onClick={() => handleActivate(u.id)} className="text-xs text-green-400 hover:underline">Activate</button>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        {/* Generate License */}
                        <div className="card">
                            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">🔑 Generate License</h3>
                            <div className="space-y-3">
                                <input type="text" value={genForm.userId} onChange={(e) => setGenForm({ ...genForm, userId: e.target.value })} className="input-field text-sm" placeholder="User ID" />
                                <select value={genForm.plan} onChange={(e) => setGenForm({ ...genForm, plan: e.target.value })} className="input-field text-sm">
                                    <option value="PRO_MONTHLY">Pro Monthly</option>
                                    <option value="PRO_YEARLY">Pro Yearly</option>
                                </select>
                                <input type="number" value={genForm.durationDays} onChange={(e) => setGenForm({ ...genForm, durationDays: Number(e.target.value) })} className="input-field text-sm" placeholder="Duration (days)" />
                                <button onClick={handleGenerateLicense} className="btn-primary w-full text-sm">Generate</button>
                            </div>
                        </div>
                    </div>
                </div>
            </Layout>
        </>
    );
}
