import { useState, useEffect } from 'react';
import { fetchUserData } from '../../api/mockApi';
import { Search, ArrowUpRight, ArrowDownRight } from 'lucide-react';

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) return '';
    const map = { Completed: 'Выполнен', Pending: 'В обработке', Failed: 'Ошибка', completed: 'Выполнен', pending: 'В обработке' };
    return map[s] || s;
};

const TransactionsHistory = () => {
    const [transactions, setTransactions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        fetchUserData().then((data) => {
            setTransactions(data.transactions || []);
            setLoading(false);
        }).catch(() => setLoading(false));
    }, []);

    const filtered = transactions.filter(tx =>
        typeLabel(tx.type, tx.direction).toLowerCase().includes(searchTerm.toLowerCase()) ||
        tx.type?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="animate-fade-in pb-20">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-end 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">Все ваши транзакции</p>
                </div>
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={16} />
                    <input type="text" placeholder="Поиск..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
                        className="bg-black-gradient-2 text-white border border-gray-700 focus:border-secondary rounded-xl pl-9 pr-4 py-2.5 font-poppins outline-none text-sm" />
                </div>
            </div>

            <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                {loading ? (
                    <div className="flex flex-col items-center justify-center py-20 gap-4">
                        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-secondary"></div>
                        <p className="text-dimWhite font-poppins text-sm">Загрузка...</p>
                    </div>
                ) : filtered.length === 0 ? (
                    <div className="py-16 text-center text-dimWhite font-poppins">Операций не найдено</div>
                ) : (
                    <div className="divide-y divide-gray-800/50">
                        {filtered.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-5 py-4 hover:bg-white/5 transition-colors">
                                    <div className="flex items-center gap-4">
                                        <div className={`w-10 h-10 rounded-full 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 font-poppins font-medium text-sm">{typeLabel(tx.type, tx.direction)}</p>
                                            <p className="text-dimWhite font-poppins text-xs mt-0.5">
                                                {tx.transaction_id || tx.id} · {new Date(tx.created_at).toLocaleDateString('ru-RU')}
                                            </p>
                                        </div>
                                    </div>
                                    <div className="text-right flex-shrink-0">
                                        <p className={`font-poppins font-semibold ${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 mt-1 inline-block ${tx.status === 'Completed' || tx.status === 'completed' ? 'bg-green-500/15 text-green-400' : 'bg-yellow-500/15 text-yellow-400'}`}>
                                            {statusLabel(tx.status)}
                                        </span>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>
        </div>
    );
};

export default TransactionsHistory;
