import { useState, useEffect } from 'react';
import { TrendingUp, DollarSign, Calendar, CheckCircle, Clock, XCircle, Plus, X, ChevronDown } from 'lucide-react';
import { fetchLoans, applyLoan } from '../../api/mockApi';
import toast from 'react-hot-toast';

const statusConfig = {
    active: { color: 'text-green-400 bg-green-400/10', icon: CheckCircle, label: 'Активный' },
    pending: { color: 'text-yellow-400 bg-yellow-400/10', icon: Clock, label: 'На рассмотрении' },
    paid: { color: 'text-blue-400 bg-blue-400/10', icon: CheckCircle, label: 'Погашен' },
    rejected: { color: 'text-red-400 bg-red-400/10', icon: XCircle, label: 'Отклонён' },
};

const TERM_OPTIONS = [
    { months: 6, label: '6 месяцев' },
    { months: 12, label: '1 год' },
    { months: 24, label: '2 года' },
    { months: 36, label: '3 года' },
    { months: 60, label: '5 лет' },
];

const LoanView = () => {
    const [loans, setLoans] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isApplying, setIsApplying] = useState(false);
    const [form, setForm] = useState({ amount: '', term_months: 12, purpose: '' });
    const [preview, setPreview] = useState(null);

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

    useEffect(() => {
        if (form.amount && !isNaN(form.amount) && parseFloat(form.amount) > 0) {
            const amount = parseFloat(form.amount);
            const months = parseInt(form.term_months);
            const r = 12 / 100 / 12;
            const monthly = amount * (r * Math.pow(1 + r, months)) / (Math.pow(1 + r, months) - 1);
            const total = monthly * months;
            setPreview({ monthly: monthly.toFixed(2), total: total.toFixed(2), interest: (total - amount).toFixed(2) });
        } else setPreview(null);
    }, [form.amount, form.term_months]);

    const loadLoans = async () => {
        setLoading(true);
        try { setLoans(await fetchLoans()); }
        catch { toast.error('Не удалось загрузить кредиты'); }
        finally { setLoading(false); }
    };

    const handleApply = async (e) => {
        e.preventDefault();
        if (!form.amount || parseFloat(form.amount) < 100) { toast.error('Минимальная сумма кредита — $100'); return; }
        setIsApplying(true);
        try {
            const res = await applyLoan({ amount: parseFloat(form.amount), term_months: parseInt(form.term_months), purpose: form.purpose });
            toast.success(res.message || 'Кредит одобрен!');
            setIsModalOpen(false);
            setForm({ amount: '', term_months: 12, purpose: '' });
            loadLoans();
        } catch (error) { toast.error(error.message || 'Ошибка заявки'); }
        finally { setIsApplying(false); }
    };

    const activeLoans = loans.filter(l => l.status === 'active');
    const totalOwed = activeLoans.reduce((s, l) => s + parseFloat(l.total_repayment) - parseFloat(l.amount_paid), 0);

    return (
        <div className="animate-fade-in pb-20">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Кредиты</h2>
                    <p className="text-dimWhite font-poppins text-sm">Оформите кредит под 12% годовых</p>
                </div>
                <button onClick={() => setIsModalOpen(true)}
                    className="flex items-center gap-2 bg-blue-gradient text-primary px-6 py-3 rounded-xl font-poppins font-medium hover:opacity-90 whitespace-nowrap">
                    <Plus size={20} /> Оформить кредит
                </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                {[
                    { label: 'Активных кредитов', value: activeLoans.length, color: 'text-white' },
                    { label: 'Общий долг', value: `$${totalOwed.toFixed(2)}`, color: 'text-red-400' },
                    { label: 'Процентная ставка', value: '12% / год', color: 'text-secondary' },
                ].map((s, i) => (
                    <div key={i} className="bg-black-gradient-2 rounded-2xl p-5 border border-gray-800">
                        <div className="text-dimWhite text-sm font-poppins mb-1">{s.label}</div>
                        <div className={`text-2xl font-poppins font-bold ${s.color}`}>{s.value}</div>
                    </div>
                ))}
            </div>

            {loading ? (
                <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>
            ) : loans.length === 0 ? (
                <div className="bg-black-gradient-2 rounded-2xl p-10 text-center border border-gray-800">
                    <TrendingUp className="mx-auto text-dimWhite mb-4" size={48} />
                    <h3 className="text-xl font-poppins text-white mb-2">Кредитов нет</h3>
                    <button onClick={() => setIsModalOpen(true)} className="bg-secondary/20 text-secondary hover:bg-secondary/30 px-6 py-2 rounded-lg font-poppins mt-4">
                        Подать заявку
                    </button>
                </div>
            ) : (
                <div className="flex flex-col gap-4">
                    {loans.map((loan) => {
                        const cfg = statusConfig[loan.status] || statusConfig.pending;
                        const StatusIcon = cfg.icon;
                        const progress = parseFloat(loan.total_repayment) > 0 ? (parseFloat(loan.amount_paid) / parseFloat(loan.total_repayment)) * 100 : 0;
                        return (
                            <div key={loan.id} className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                                <div className="flex items-center gap-3 mb-4">
                                    <span className={`flex items-center gap-1 text-xs font-poppins px-3 py-1 rounded-full ${cfg.color}`}>
                                        <StatusIcon size={12} /> {cfg.label}
                                    </span>
                                    {loan.purpose && <span className="text-dimWhite text-xs font-poppins">{loan.purpose}</span>}
                                </div>
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-3">
                                    {[
                                        ['Сумма', `$${parseFloat(loan.amount).toFixed(2)}`],
                                        ['Ежемесячно', `$${parseFloat(loan.monthly_payment).toFixed(2)}`],
                                        ['Срок', `${loan.term_months} мес.`],
                                        ['К возврату', `$${parseFloat(loan.total_repayment).toFixed(2)}`],
                                    ].map(([label, val]) => (
                                        <div key={label}>
                                            <div className="text-dimWhite text-xs font-poppins mb-0.5">{label}</div>
                                            <div className="text-white font-poppins font-semibold">{val}</div>
                                        </div>
                                    ))}
                                </div>
                                {loan.status === 'active' && (
                                    <div className="mt-2">
                                        <div className="flex justify-between text-xs font-poppins text-dimWhite mb-1">
                                            <span>Оплачено: ${parseFloat(loan.amount_paid).toFixed(2)}</span>
                                            <span>{progress.toFixed(0)}%</span>
                                        </div>
                                        <div className="w-full bg-gray-800 rounded-full h-2">
                                            <div className="bg-gradient-to-r from-secondary to-blue-400 h-2 rounded-full" style={{ width: `${Math.min(progress, 100)}%` }} />
                                        </div>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}

            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
                    <div className="bg-gray-900 border border-gray-700 w-full max-w-lg rounded-2xl p-6 shadow-2xl animate-fade-in relative overflow-hidden max-h-[90vh] overflow-y-auto">
                        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-secondary to-purple-500" />
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="text-2xl font-poppins font-semibold text-white">Оформить кредит</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-white"><X size={24} /></button>
                        </div>
                        <form onSubmit={handleApply} className="space-y-4">
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Сумма кредита ($)</label>
                                <div className="relative">
                                    <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                                    <input type="number" min="100" max="100000" value={form.amount} onChange={(e) => setForm(f => ({ ...f, amount: e.target.value }))}
                                        className="w-full bg-black/40 border border-gray-700 rounded-xl pl-10 pr-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="например: 5000" required />
                                </div>
                            </div>
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Срок погашения</label>
                                <div className="relative">
                                    <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                                    <select value={form.term_months} onChange={(e) => setForm(f => ({ ...f, term_months: e.target.value }))}
                                        className="w-full bg-black/40 border border-gray-700 rounded-xl pl-10 pr-10 py-3 text-white font-poppins focus:outline-none focus:border-secondary appearance-none">
                                        {TERM_OPTIONS.map(o => <option key={o.months} value={o.months} className="bg-gray-800">{o.label}</option>)}
                                    </select>
                                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 text-dimWhite pointer-events-none" size={16} />
                                </div>
                            </div>
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Цель кредита (необязательно)</label>
                                <input type="text" value={form.purpose} onChange={(e) => setForm(f => ({ ...f, purpose: e.target.value }))}
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="например: Ремонт, автомобиль..." />
                            </div>
                            {preview && (
                                <div className="bg-secondary/10 border border-secondary/30 rounded-xl p-4">
                                    <div className="text-secondary font-poppins font-semibold mb-3 text-sm">Предварительный расчёт</div>
                                    <div className="grid grid-cols-3 gap-2 text-center">
                                        {[['В месяц', `$${preview.monthly}`, 'text-white'], ['Переплата', `$${preview.interest}`, 'text-red-400'], ['Итого', `$${preview.total}`, 'text-white']].map(([l, v, c]) => (
                                            <div key={l}><div className="text-dimWhite text-xs font-poppins mb-0.5">{l}</div><div className={`font-poppins font-bold ${c}`}>{v}</div></div>
                                        ))}
                                    </div>
                                </div>
                            )}
                            <button type="submit" disabled={isApplying}
                                className={`w-full py-3 rounded-xl font-poppins font-semibold transition-all ${isApplying ? 'bg-gray-600 text-gray-300 cursor-not-allowed' : 'bg-blue-gradient text-primary hover:opacity-90'}`}>
                                {isApplying ? 'Обработка...' : 'Подать заявку'}
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default LoanView;
