import { useState, useEffect } from 'react';
import { fetchUserData } from '../../api/mockApi';
import {
    ArrowUpRight, ArrowDownRight, Send, TrendingUp,
    ArrowDownCircle, CreditCard, Zap, Globe2,
    ChevronRight, Wallet, Sparkles
} from 'lucide-react';
import { Link } from 'react-router-dom';

const SkeletonCard = () => (
    <div className="animate-pulse bg-gradient-to-br from-blue-900/40 to-indigo-900/30 rounded-3xl h-44 border border-blue-800/30" />
);

const QuickAction = ({ to, icon: Icon, label, gradient, glow }) => (
    <Link to={to}
        className={`relative flex flex-col items-center gap-2.5 p-4 rounded-2xl border border-white/5 overflow-hidden group hover:scale-105 transition-all duration-200 ${gradient}`}>
        <div className={`absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-xl ${glow}`} />
        <div className="relative z-10 w-12 h-12 rounded-2xl bg-white/10 backdrop-blur-sm flex items-center justify-center border border-white/10">
            <Icon size={22} className="text-white" />
        </div>
        <span className="relative z-10 text-white text-xs font-poppins font-semibold text-center">{label}</span>
    </Link>
);

const StatCard = ({ label, value, change, positive, icon: Icon, color }) => (
    <div className="bg-black-gradient-2 rounded-2xl p-5 border border-gray-800 hover:border-gray-700 transition-colors">
        <div className="flex items-center justify-between mb-4">
            <p className="text-dimWhite font-poppins text-sm">{label}</p>
            <div className={`p-2 rounded-xl ${color}`}><Icon size={16} className={positive ? 'text-green-400' : 'text-red-400'} /></div>
        </div>
        <h4 className="text-white font-poppins font-bold text-2xl mb-1">{value}</h4>
        <p className={`text-xs font-poppins flex items-center gap-1 ${positive ? 'text-green-400' : 'text-red-400'}`}>
            {positive ? <ArrowUpRight size={12}/> : <ArrowDownRight size={12}/>}
            {change}
        </p>
    </div>
);

const Overview = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    const userStr = localStorage.getItem('iosco_user');
    const user = userStr ? JSON.parse(userStr) : null;

    useEffect(() => {
        fetchUserData().then(res => { setData(res); setLoading(false); });
    }, []);

    if (loading) return (
        <div className="animate-fade-in space-y-6 pb-28">
            <SkeletonCard />
            <div className="grid grid-cols-4 gap-3">
                {[...Array(4)].map((_, i) => <div key={i} className="animate-pulse bg-white/5 rounded-2xl h-24 border border-gray-800" />)}
            </div>
            <div className="animate-pulse bg-white/5 rounded-2xl h-48 border border-gray-800" />
        </div>
    );

    const typeLabel = (type, direction) => {
        if (type === 'Deposit') return 'Пополнение';
        if (type === 'Loan Disbursement') return 'Выдача кредита';
        if (type === 'Transfer') return direction === 'Sent' ? 'Перевод отправлен' : 'Перевод получен';
        return type;
    };

    const statusLabel = (s) => {
        if (s === 'Completed') return 'Выполнен';
        if (s === 'Pending') return 'В обработке';
        if (s === 'Failed') return 'Ошибка';
        return s;
    };

    const balance = parseFloat(data.balance || 0);
    const firstName = (user?.full_name || user?.username || 'Клиент').split(' ')[0];

    const quickActions = [
        { to: '/dashboard/transfer',  icon: Send,           label: 'Перевод',  gradient: 'bg-gradient-to-br from-blue-600/20 to-blue-800/10',   glow: 'bg-blue-500/30' },
        { to: '/dashboard/topup',     icon: ArrowDownCircle,label: 'Пополнить',gradient: 'bg-gradient-to-br from-green-600/20 to-emerald-800/10', glow: 'bg-green-500/30' },
        { to: '/dashboard/payments',  icon: Zap,            label: 'Платежи',  gradient: 'bg-gradient-to-br from-yellow-600/20 to-orange-800/10', glow: 'bg-yellow-500/30' },
        { to: '/dashboard/loans',     icon: TrendingUp,     label: 'Кредит',   gradient: 'bg-gradient-to-br from-purple-600/20 to-purple-800/10', glow: 'bg-purple-500/30' },
        { to: '/dashboard/currency',  icon: Globe2,         label: 'Валюта',   gradient: 'bg-gradient-to-br from-cyan-600/20 to-teal-800/10',    glow: 'bg-cyan-500/30' },
        { to: '/dashboard/cards',     icon: CreditCard,     label: 'Карты',    gradient: 'bg-gradient-to-br from-rose-600/20 to-pink-800/10',    glow: 'bg-rose-500/30' },
    ];

    return (
        <div className="animate-fade-in pb-28 md:pb-10">
            {/* Hero Balance Card */}
            <div className="relative rounded-3xl overflow-hidden mb-7 shadow-2xl shadow-blue-900/40">
                <div className="absolute inset-0 bg-gradient-to-br from-blue-700 via-blue-800 to-indigo-950" />
                <div className="absolute inset-0 opacity-20"
                    style={{ backgroundImage: 'radial-gradient(ellipse at 85% 20%, rgba(255,255,255,0.4) 0%, transparent 55%), radial-gradient(ellipse at 10% 80%, rgba(51,187,207,0.6) 0%, transparent 55%)' }} />
                <div className="absolute bottom-0 right-0 w-56 h-56 bg-white/5 rounded-full -mr-16 -mb-16" />
                <div className="absolute top-0 right-14 w-28 h-28 bg-white/5 rounded-full -mt-10" />
                <div className="absolute top-0 left-0 w-full h-full"
                    style={{ backgroundImage: 'url("data:image/svg+xml,%3Csvg width=\'60\' height=\'60\' viewBox=\'0 0 60 60\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cg fill=\'none\' fill-rule=\'evenodd\'%3E%3Cg fill=\'%23ffffff\' fill-opacity=\'0.03\'%3E%3Cpath d=\'M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z\'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")' }} />

                <div className="relative z-10 p-7">
                    <div className="flex items-start justify-between mb-6">
                        <div>
                            <p className="text-white/60 font-poppins text-sm mb-0.5">Добро пожаловать,</p>
                            <h2 className="text-white font-poppins font-bold text-2xl">{firstName} <Sparkles size={16} className="inline text-yellow-300 mb-1" /></h2>
                        </div>
                        <div className="flex items-center gap-2 bg-white/10 rounded-xl px-3 py-1.5 border border-white/10">
                            <div className="w-2 h-2 rounded-full bg-green-400 animate-pulse" />
                            <span className="text-white/80 text-xs font-poppins">Активен</span>
                        </div>
                    </div>

                    <div className="mb-2">
                        <p className="text-white/50 font-poppins text-xs uppercase tracking-widest mb-1.5">Общий баланс</p>
                        <div className="text-white font-poppins font-bold text-5xl tracking-tight">
                            ${balance.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </div>
                    </div>

                    <div className="flex items-center justify-between mt-4 pt-4 border-t border-white/10">
                        <div className="flex items-center gap-2">
                            <Wallet size={13} className="text-white/50" />
                            <span className="text-white/50 text-xs font-poppins">Счёт: {data.accountNumber || '—'}</span>
                        </div>
                        <div className="flex items-center gap-1 bg-green-500/20 text-green-300 text-xs font-poppins px-2.5 py-1 rounded-full border border-green-500/20">
                            <TrendingUp size={11} /> +2.5%
                        </div>
                    </div>
                </div>
            </div>

            {/* Quick Actions */}
            <div className="grid grid-cols-3 md:grid-cols-6 gap-3 mb-7">
                {quickActions.map(a => <QuickAction key={a.to} {...a} />)}
            </div>

            {/* Stats */}
            <div className="grid grid-cols-2 gap-4 mb-7">
                <StatCard label="Доходы" value="$8 240.50" change="+2.5% за месяц" positive icon={ArrowUpRight} color="bg-green-500/10" />
                <StatCard label="Расходы" value="$3 420.00" change="-1.2% за месяц" positive={false} icon={ArrowDownRight} color="bg-red-500/10" />
            </div>

            {/* Recent Transactions */}
            <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                <div className="flex justify-between items-center px-6 py-4 border-b border-gray-800">
                    <h3 className="text-base font-poppins font-semibold text-white">Последние операции</h3>
                    <Link to="/dashboard/history" className="flex items-center gap-1 text-secondary font-poppins text-sm hover:underline">
                        Все <ChevronRight size={14} />
                    </Link>
                </div>

                {data.transactions.length === 0 ? (
                    <div className="text-center py-12 text-dimWhite font-poppins text-sm">
                        <div className="w-12 h-12 rounded-2xl bg-white/5 flex items-center justify-center mx-auto mb-3">
                            <Wallet size={22} className="text-dimWhite/50" />
                        </div>
                        Операций пока нет
                    </div>
                ) : (
                    <div className="divide-y divide-gray-800/50">
                        {data.transactions.slice(0, 6).map((tx) => {
                            const isIncoming = tx.direction === 'Received' || tx.type === 'Deposit' || tx.type === 'Loan Disbursement';
                            return (
                                <div key={tx.id} className="flex items-center justify-between px-6 py-4 hover:bg-white/[0.02] transition-colors">
                                    <div className="flex items-center gap-3">
                                        <div className={`w-10 h-10 rounded-2xl flex items-center justify-center flex-shrink-0 ${isIncoming ? 'bg-green-500/15' : 'bg-red-500/15'}`}>
                                            {isIncoming
                                                ? <ArrowDownRight size={18} className="text-green-400" />
                                                : <ArrowUpRight size={18} className="text-red-400" />}
                                        </div>
                                        <div>
                                            <p className="text-white text-sm font-poppins font-medium">{typeLabel(tx.type, tx.direction)}</p>
                                            <p className="text-dimWhite text-xs font-poppins">{new Date(tx.created_at).toLocaleDateString('ru-RU')}</p>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <p className={`font-poppins font-bold text-sm ${isIncoming ? 'text-green-400' : 'text-red-400'}`}>
                                            {isIncoming ? '+' : '-'}${parseFloat(tx.amount).toFixed(2)}
                                        </p>
                                        <span className={`text-[10px] font-poppins px-2 py-0.5 rounded-full ${
                                            tx.status === 'Completed' ? 'bg-green-500/10 text-green-400' :
                                            tx.status === 'Pending'   ? 'bg-yellow-500/10 text-yellow-400' :
                                            'bg-red-500/10 text-red-400'
                                        }`}>{statusLabel(tx.status)}</span>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>
        </div>
    );
};

export default Overview;
