import { useState, useEffect } from 'react';
import { CreditCard, Search, Shield, ShieldOff } from 'lucide-react';
import { fetchAllCards } from '../../api/mockApi';
import toast from 'react-hot-toast';

const AdminCards = () => {
    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');

    useEffect(() => { fetchAllCards().then(d => { setCards(d); setLoading(false); }).catch(() => { toast.error('Ошибка загрузки'); setLoading(false); }); }, []);

    const filtered = cards.filter(c =>
        c.card_holder_name?.toLowerCase().includes(search.toLowerCase()) ||
        c.username?.toLowerCase().includes(search.toLowerCase()) ||
        c.card_number?.includes(search)
    );

    const maskCard = (num) => num ? num.slice(0, 4) + ' •••• •••• ' + num.slice(-4) : '•••• •••• •••• ••••';

    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">{cards.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="Поиск карты..." />
                </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">
                                    {['Номер карты', 'Держатель', 'Владелец', 'Тип', 'Срок', 'Баланс', 'Статус'].map(h => (
                                        <th key={h} className="text-left text-dimWhite font-poppins text-xs font-medium px-5 py-4">{h}</th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {filtered.map((card) => (
                                    <tr key={card.id} className="border-b border-gray-800/50 hover:bg-white/5 transition-colors">
                                        <td className="px-5 py-4 text-white font-poppins text-sm">{maskCard(card.card_number)}</td>
                                        <td className="px-5 py-4 text-white font-poppins text-sm">{card.card_holder_name}</td>
                                        <td className="px-5 py-4">
                                            <div className="text-white text-sm font-poppins">{card.full_name}</div>
                                            <div className="text-dimWhite text-xs font-poppins">@{card.username}</div>
                                        </td>
                                        <td className="px-5 py-4">
                                            <span className={`text-xs font-poppins px-2 py-1 rounded-full ${card.card_type === 'credit' ? 'bg-purple-500/20 text-purple-400' : 'bg-blue-500/20 text-blue-400'}`}>
                                                {card.card_type === 'credit' ? 'Кредитная' : 'Дебетовая'}
                                            </span>
                                        </td>
                                        <td className="px-5 py-4 text-dimWhite font-poppins text-sm">{card.expiration_date}</td>
                                        <td className="px-5 py-4 text-white font-poppins text-sm">${parseFloat(card.balance || 0).toFixed(2)}</td>
                                        <td className="px-5 py-4">
                                            <span className={`flex items-center gap-1 text-xs font-poppins w-fit px-2 py-1 rounded-full ${card.status === 'active' ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'}`}>
                                                {card.status === 'active' ? <Shield size={10} /> : <ShieldOff size={10} />}
                                                {card.status === 'active' ? 'Активна' : 'Заблокирована'}
                                            </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 AdminCards;
