import { useState, useEffect } from 'react';
import { Activity, Search } from 'lucide-react';
import { fetchAllTransactions } from '../../api/mockApi';

const typeRu = (type) => {
    const map = { Transfer: 'Перевод', Deposit: 'Пополнение', 'Loan Disbursement': 'Кредит' };
    return map[type] || type;
};

const AdminTransactions = () => {
    const [transactions, setTransactions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');

    useEffect(() => { fetchAllTransactions().then(d => { setTransactions(d); setLoading(false); }).catch(() => setLoading(false)); }, []);

    const filtered = transactions.filter(t =>
        t.transaction_id?.toLowerCase().includes(search.toLowerCase()) ||
        t.sender_username?.toLowerCase().includes(search.toLowerCase()) ||
        t.receiver_username?.toLowerCase().includes(search.toLowerCase())
    );

    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">{transactions.length} записей</p>
                </div>
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={16} />
                    <input type="text" value={search} onChange={(e) => setSearch(e.target.value)}
                        className="bg-black-gradient-2 border border-gray-700 rounded-xl pl-9 pr-4 py-2 text-white font-poppins text-sm focus:outline-none focus:border-secondary"
                        placeholder="ID, пользователь..." />
                </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>
            ) : (
                <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                    <div className="overflow-x-auto">
                        <table className="w-full">
                            <thead>
                                <tr className="border-b border-gray-800">
                                    {['ID транзакции', 'Отправитель', 'Получатель', 'Тип', 'Сумма', 'Дата', 'Статус'].map(h => (
                                        <th key={h} className="text-left text-dimWhite font-poppins text-xs font-medium px-4 py-4">{h}</th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {filtered.map((t, i) => (
                                    <tr key={i} className="border-b border-gray-800/50 hover:bg-white/5 transition-colors">
                                        <td className="px-4 py-3 font-mono text-xs text-dimWhite">{t.transaction_id}</td>
                                        <td className="px-4 py-3 text-white font-poppins text-sm">{t.sender_username ? `@${t.sender_username}` : '—'}</td>
                                        <td className="px-4 py-3 text-white font-poppins text-sm">{t.receiver_username ? `@${t.receiver_username}` : '—'}</td>
                                        <td className="px-4 py-3 text-dimWhite font-poppins text-sm">{typeRu(t.type)}</td>
                                        <td className="px-4 py-3 text-green-400 font-poppins text-sm font-semibold">${parseFloat(t.amount).toFixed(2)}</td>
                                        <td className="px-4 py-3 text-dimWhite font-poppins text-xs">{new Date(t.created_at).toLocaleString('ru-RU')}</td>
                                        <td className="px-4 py-3">
                                            <span className={`px-2 py-1 rounded-full text-xs font-poppins ${t.status === 'Completed' ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400'}`}>
                                                {t.status === 'Completed' ? 'Выполнен' : 'В обработке'}
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                                {filtered.length === 0 && <tr><td colSpan="7" className="text-center py-10 text-dimWhite font-poppins">Транзакции не найдены</td></tr>}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminTransactions;
