import { useState, useEffect } from 'react';
import { Users, UserPlus, Trash2, Edit2, X, DollarSign, Search, Shield } from 'lucide-react';
import { fetchAllUsers, createAdminUser, updateAdminUser, deleteAdminUser, adjustBalance } from '../../api/mockApi';
import toast from 'react-hot-toast';

const AdminUsers = () => {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [editingUser, setEditingUser] = useState(null);
    const [balanceModal, setBalanceModal] = useState(null);
    const [balanceAmount, setBalanceAmount] = useState('');
    const [formData, setFormData] = useState({ username: '', email: '', full_name: '', password: '', role: 'user' });

    const loadUsers = async () => {
        setLoading(true);
        try { setUsers(await fetchAllUsers()); }
        catch { toast.error('Ошибка загрузки пользователей'); }
        finally { setLoading(false); }
    };

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

    const openCreate = () => { setEditingUser(null); setFormData({ username: '', email: '', full_name: '', password: '', role: 'user' }); setIsModalOpen(true); };
    const openEdit = (u) => { setEditingUser(u); setFormData({ username: u.username, email: u.email, full_name: u.full_name, password: '', role: u.role }); setIsModalOpen(true); };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            if (editingUser) { await updateAdminUser({ id: editingUser.id, full_name: formData.full_name, email: formData.email, role: formData.role }); toast.success('Пользователь обновлён!'); }
            else { await createAdminUser(formData); toast.success('Пользователь создан!'); }
            setIsModalOpen(false);
            loadUsers();
        } catch (e) { toast.error(e.message || 'Ошибка'); }
        finally { setIsSubmitting(false); }
    };

    const handleDelete = async (u) => {
        if (!confirm(`Удалить @${u.username}? Это действие необратимо.`)) return;
        try { await deleteAdminUser(u.id); toast.success('Пользователь удалён'); loadUsers(); }
        catch (e) { toast.error(e.message || 'Ошибка'); }
    };

    const handleAdjustBalance = async (e) => {
        e.preventDefault();
        if (!balanceAmount || isNaN(balanceAmount)) return;
        try { await adjustBalance(balanceModal.id, parseFloat(balanceAmount)); toast.success('Баланс изменён!'); setBalanceModal(null); setBalanceAmount(''); loadUsers(); }
        catch (e) { toast.error(e.message || 'Ошибка'); }
    };

    const filtered = users.filter(u =>
        u.full_name?.toLowerCase().includes(search.toLowerCase()) ||
        u.username?.toLowerCase().includes(search.toLowerCase()) ||
        u.email?.toLowerCase().includes(search.toLowerCase())
    );

    return (
        <div className="w-full relative pb-20 animate-fade-in">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-1">Пользователи</h2>
                    <p className="text-dimWhite font-poppins text-sm">{users.length} зарегистрировано</p>
                </div>
                <div className="flex items-center gap-3">
                    <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>
                    <button onClick={openCreate} className="flex items-center gap-2 bg-blue-gradient text-primary px-5 py-2 rounded-xl font-poppins font-medium hover:opacity-90 text-sm whitespace-nowrap">
                        <UserPlus size={16} /> Добавить
                    </button>
                </div>
            </div>

            <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                {loading ? (
                    <div className="flex justify-center py-16"><div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-secondary"></div></div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full">
                            <thead>
                                <tr className="border-b border-gray-800">
                                    {['Пользователь', 'Email', 'Баланс', 'Роль', 'Статус', 'Дата', 'Действия'].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 className="font-poppins">
                                {filtered.map((u) => (
                                    <tr key={u.id} className="border-b border-gray-800/50 hover:bg-white/5 transition-colors">
                                        <td className="px-4 py-3">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-full bg-blue-gradient flex items-center justify-center text-primary font-bold text-sm flex-shrink-0">
                                                    {u.full_name?.[0]?.toUpperCase() || '?'}
                                                </div>
                                                <div>
                                                    <div className="text-white text-sm font-medium">{u.full_name}</div>
                                                    <div className="text-dimWhite text-xs">@{u.username}</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-4 py-3 text-dimWhite text-sm">{u.email}</td>
                                        <td className="px-4 py-3 text-white text-sm font-semibold">${parseFloat(u.balance || 0).toFixed(2)}</td>
                                        <td className="px-4 py-3">
                                            <span className={`px-2 py-1 rounded-full text-xs font-medium uppercase ${u.role === 'admin' ? 'bg-secondary/20 text-secondary' : 'bg-gray-800 text-dimWhite'}`}>
                                                {u.role === 'admin' ? 'Админ' : 'Клиент'}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className={`flex items-center gap-1 text-xs w-fit px-2 py-1 rounded-full ${u.account_status === 'active' || !u.account_status ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'}`}>
                                                <Shield size={10} /> {u.account_status === 'active' || !u.account_status ? 'Активен' : 'Заблокирован'}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-dimWhite text-xs">{new Date(u.created_at).toLocaleDateString('ru-RU')}</td>
                                        <td className="px-4 py-3">
                                            <div className="flex items-center gap-2">
                                                <button onClick={() => { setBalanceModal(u); setBalanceAmount(''); }} className="text-green-400 hover:text-green-300 p-1 transition-colors" title="Баланс"><DollarSign size={15} /></button>
                                                <button onClick={() => openEdit(u)} className="text-secondary hover:text-white p-1 transition-colors" title="Редактировать"><Edit2 size={15} /></button>
                                                <button onClick={() => handleDelete(u)} className="text-dimWhite hover:text-red-400 p-1 transition-colors" title="Удалить"><Trash2 size={15} /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                                {filtered.length === 0 && <tr><td colSpan="7" className="py-10 text-center text-dimWhite">Пользователи не найдены</td></tr>}
                            </tbody>
                        </table>
                    </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">
                        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-secondary to-blue-500" />
                        <div className="flex justify-between items-center mb-5">
                            <h3 className="text-xl font-poppins font-semibold text-white">{editingUser ? 'Редактировать' : 'Новый пользователь'}</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-white"><X size={22} /></button>
                        </div>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Полное имя</label>
                                <input type="text" value={formData.full_name} onChange={(e) => setFormData(f => ({ ...f, full_name: e.target.value }))} required
                                    className="w-full bg-black/30 border border-gray-700 text-white rounded-xl px-4 py-3 focus:outline-none focus:border-secondary font-poppins" placeholder="Иван Иванов" />
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-dimWhite text-sm font-poppins mb-1.5">Логин</label>
                                    <input type="text" value={formData.username} onChange={(e) => setFormData(f => ({ ...f, username: e.target.value }))} required disabled={!!editingUser}
                                        className="w-full bg-black/30 border border-gray-700 text-white rounded-xl px-4 py-3 focus:outline-none focus:border-secondary font-poppins disabled:opacity-50" placeholder="ivanov123" />
                                </div>
                                <div>
                                    <label className="block text-dimWhite text-sm font-poppins mb-1.5">Email</label>
                                    <input type="email" value={formData.email} onChange={(e) => setFormData(f => ({ ...f, email: e.target.value }))} required
                                        className="w-full bg-black/30 border border-gray-700 text-white rounded-xl px-4 py-3 focus:outline-none focus:border-secondary font-poppins" />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                {!editingUser && (
                                    <div>
                                        <label className="block text-dimWhite text-sm font-poppins mb-1.5">Пароль</label>
                                        <input type="password" value={formData.password} onChange={(e) => setFormData(f => ({ ...f, password: e.target.value }))} required
                                            className="w-full bg-black/30 border border-gray-700 text-white rounded-xl px-4 py-3 focus:outline-none focus:border-secondary font-poppins" placeholder="Мин. 8 символов" />
                                    </div>
                                )}
                                <div>
                                    <label className="block text-dimWhite text-sm font-poppins mb-1.5">Роль</label>
                                    <select value={formData.role} onChange={(e) => setFormData(f => ({ ...f, role: e.target.value }))}
                                        className="w-full bg-black/30 border border-gray-700 text-white rounded-xl px-4 py-3 focus:outline-none focus:border-secondary font-poppins">
                                        <option value="user" className="bg-gray-800">Клиент</option>
                                        <option value="admin" className="bg-gray-800">Администратор</option>
                                    </select>
                                </div>
                            </div>
                            <button type="submit" disabled={isSubmitting}
                                className={`w-full py-3 rounded-xl font-poppins font-semibold transition-all ${isSubmitting ? 'bg-gray-600 text-gray-300' : 'bg-blue-gradient text-primary hover:opacity-90'}`}>
                                {isSubmitting ? 'Сохранение...' : (editingUser ? 'Обновить' : 'Создать')}
                            </button>
                        </form>
                    </div>
                </div>
            )}

            {/* Модалка баланс */}
            {balanceModal && (
                <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-sm rounded-2xl p-6 shadow-2xl animate-fade-in relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-green-500 to-teal-500" />
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-xl font-poppins font-semibold text-white">Изменить баланс</h3>
                            <button onClick={() => setBalanceModal(null)} className="text-gray-400 hover:text-white"><X size={22} /></button>
                        </div>
                        <p className="text-dimWhite font-poppins text-sm mb-1">Пользователь: <span className="text-white">@{balanceModal.username}</span></p>
                        <p className="text-dimWhite font-poppins text-sm mb-4">Текущий баланс: <span className="text-white">${parseFloat(balanceModal.balance || 0).toFixed(2)}</span></p>
                        <form onSubmit={handleAdjustBalance} 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={16} />
                                    <input type="number" step="0.01" value={balanceAmount} onChange={(e) => setBalanceAmount(e.target.value)}
                                        className="w-full bg-black/40 border border-gray-700 text-white rounded-xl pl-9 pr-4 py-3 focus:outline-none focus:border-secondary font-poppins"
                                        placeholder="500 или -100" required />
                                </div>
                            </div>
                            <button type="submit" className="w-full py-3 rounded-xl font-poppins font-semibold bg-green-500/20 text-green-400 hover:bg-green-500/30 transition-all border border-green-500/30">
                                Применить
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminUsers;
