import { useState, useEffect } from 'react';
import { Users, CreditCard, TrendingUp, DollarSign, Activity, ArrowUpRight, Clock, CheckCircle } from 'lucide-react';
import { fetchAdminStats } from '../../api/mockApi';

const StatCard = ({ title, value, icon: Icon, color }) => (
    <div className="bg-black-gradient-2 rounded-2xl p-5 border border-gray-800 hover:border-gray-700 transition-all">
        <div className="flex items-start justify-between mb-3">
            <div className={`w-11 h-11 rounded-xl flex items-center justify-center ${color}`}>
                <Icon size={20} className="text-white" />
            </div>
        </div>
        <div className="text-white text-2xl font-poppins font-bold mb-0.5">{value}</div>
        <div className="text-dimWhite text-sm font-poppins">{title}</div>
    </div>
);

const AdminPanel = () => {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => { fetchAdminStats().then(d => { setStats(d); setLoading(false); }); }, []);

    if (loading) return <div className="flex justify-center py-20"><div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-secondary"></div></div>;

    const fmt = (v) => '$' + parseFloat(v || 0).toLocaleString('ru-RU', { minimumFractionDigits: 2 });

    return (
        <div className="animate-fade-in pb-20">
            <div className="mb-8">
                <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Дашборд администратора</h2>
                <p className="text-dimWhite font-poppins text-sm">Обзор всей активности банка</p>
            </div>

            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                <StatCard title="Пользователей" value={stats?.total_users ?? 0} icon={Users} color="bg-blue-500/20" />
                <StatCard title="Общий баланс" value={fmt(stats?.total_balance)} icon={DollarSign} color="bg-green-500/20" />
                <StatCard title="Транзакций" value={stats?.total_transactions ?? 0} icon={Activity} color="bg-purple-500/20" />
                <StatCard title="Карт выпущено" value={stats?.total_cards ?? 0} icon={CreditCard} color="bg-pink-500/20" />
                <StatCard title="Активных кредитов" value={stats?.active_loans ?? 0} icon={TrendingUp} color="bg-orange-500/20" />
                <StatCard title="Портфель кредитов" value={fmt(stats?.total_loan_amount)} icon={TrendingUp} color="bg-red-500/20" />
                <StatCard title="Всего пополнений" value={fmt(stats?.total_deposits)} icon={ArrowUpRight} color="bg-teal-500/20" />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                    <h3 className="text-white font-poppins font-semibold mb-4 flex items-center gap-2"><Users size={18} className="text-secondary" /> Новые пользователи</h3>
                    {stats?.recent_users?.length > 0 ? (
                        <div className="space-y-3">
                            {stats.recent_users.map((u, i) => (
                                <div key={i} className="flex items-center justify-between p-3 bg-black/30 rounded-xl border border-gray-800/50">
                                    <div className="flex items-center gap-3">
                                        <div className="w-8 h-8 rounded-full bg-blue-gradient flex items-center justify-center text-primary font-bold text-sm">{u.full_name?.[0]?.toUpperCase() || '?'}</div>
                                        <div>
                                            <div className="text-white text-sm font-poppins font-medium">{u.full_name}</div>
                                            <div className="text-dimWhite text-xs font-poppins">@{u.username}</div>
                                        </div>
                                    </div>
                                    <div className="text-dimWhite text-xs font-poppins">{new Date(u.created_at).toLocaleDateString('ru-RU')}</div>
                                </div>
                            ))}
                        </div>
                    ) : <div className="text-dimWhite text-sm font-poppins text-center py-6">Пользователей нет</div>}
                </div>

                <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                    <h3 className="text-white font-poppins font-semibold mb-4 flex items-center gap-2"><Activity size={18} className="text-secondary" /> Последние транзакции</h3>
                    {stats?.recent_transactions?.length > 0 ? (
                        <div className="space-y-3">
                            {stats.recent_transactions.map((tx, i) => (
                                <div key={i} className="flex items-center justify-between p-3 bg-black/30 rounded-xl border border-gray-800/50">
                                    <div className="flex items-center gap-3">
                                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${tx.status === 'Completed' ? 'bg-green-500/20' : 'bg-yellow-500/20'}`}>
                                            {tx.status === 'Completed' ? <CheckCircle size={14} className="text-green-400" /> : <Clock size={14} className="text-yellow-400" />}
                                        </div>
                                        <div>
                                            <div className="text-white text-sm font-poppins font-medium">{tx.type}</div>
                                            <div className="text-dimWhite text-xs font-poppins">{tx.sender ? `@${tx.sender}` : 'Система'} → {tx.receiver ? `@${tx.receiver}` : 'Система'}</div>
                                        </div>
                                    </div>
                                    <div className="text-white text-sm font-poppins font-semibold">${parseFloat(tx.amount).toFixed(2)}</div>
                                </div>
                            ))}
                        </div>
                    ) : <div className="text-dimWhite text-sm font-poppins text-center py-6">Транзакций нет</div>}
                </div>
            </div>
        </div>
    );
};

export default AdminPanel;
