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 } from 'recharts';

export default function AdminRevenue() {
    const [revenue, setRevenue] = useState<any>(null);
    const [loading, setLoading] = useState(true);

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

    const loadRevenue = async () => {
        try {
            const { data } = await adminAPI.getRevenue(12);
            setRevenue(data.data);
        } catch (err) { console.error(err); }
        setLoading(false);
    };

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

    const chartData = 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>Revenue Report – MarketScope Admin</title></Head>
            <Layout requireAdmin>
                <div className="animate-fade-in">
                    <h1 className="text-2xl font-bold mb-6">💰 Revenue Report</h1>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Total Revenue</p>
                            <p className="text-3xl font-bold text-yellow-400 mt-1">{formatIDR(revenue?.totalRevenue || 0)}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Avg Monthly</p>
                            <p className="text-3xl font-bold text-green-400 mt-1">
                                {formatIDR((revenue?.totalRevenue || 0) / (chartData.length || 1))}
                            </p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase">Last Month</p>
                            <p className="text-3xl font-bold text-blue-400 mt-1">
                                {chartData.length > 0 ? formatIDR(chartData[chartData.length - 1].revenue) : 'Rp 0'}
                            </p>
                        </div>
                    </div>

                    <div className="card">
                        <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-8">Revenue Trend (Last 12 Months)</h3>
                        <div className="h-96">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={chartData}>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                                    <XAxis dataKey="month" tick={{ fill: '#94a3b8', fontSize: 11 }} axisLine={false} tickLine={false} dy={10} />
                                    <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={(v) => `${(v / 1000000).toFixed(1)}jt`} axisLine={false} tickLine={false} />
                                    <Tooltip
                                        contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 12, boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)' }}
                                        formatter={(v: number) => [formatIDR(v), 'Revenue']}
                                    />
                                    <Bar dataKey="revenue" fill="#3b82f6" radius={[6, 6, 0, 0]} barSize={40} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                </div>
            </Layout>
        </>
    );
}
