import { useState } from 'react';
import { sendMoney } from '../../api/mockApi';
import { Send, AlertCircle, CheckCircle2, User, Hash, DollarSign, FileText } from 'lucide-react';
import toast from 'react-hot-toast';

const TransferMoney = () => {
    const [formData, setFormData] = useState({ recipientName: '', accountNumber: '', amount: '', note: '' });
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState({});

    const validate = () => {
        const e = {};
        if (!formData.recipientName) e.recipientName = 'Введите имя получателя';
        if (!formData.accountNumber || formData.accountNumber.length < 8) e.accountNumber = 'Введите корректный номер счёта (мин. 8 цифр)';
        if (!formData.amount || isNaN(formData.amount) || Number(formData.amount) <= 0) e.amount = 'Введите корректную сумму';
        setErrors(e);
        return Object.keys(e).length === 0;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!validate()) return;
        setLoading(true);
        try {
            await sendMoney({ ...formData, amount: Number(formData.amount) });
            toast.success(`Перевод $${formData.amount} выполнен успешно!`);
            setFormData({ recipientName: '', accountNumber: '', amount: '', note: '' });
        } catch (err) {
            toast.error(err.message || 'Перевод не выполнен. Проверьте баланс.');
        } finally {
            setLoading(false);
        }
    };

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
        if (errors[e.target.name]) setErrors({ ...errors, [e.target.name]: null });
    };

    const QUICK_AMOUNTS = [50, 100, 250, 500, 1000];

    return (
        <div className="animate-fade-in max-w-2xl mx-auto pb-20">
            <div className="mb-8">
                <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Перевод</h2>
                <p className="text-dimWhite font-poppins">Быстро и безопасно переводите деньги.</p>
            </div>

            <div className="bg-black-gradient-2 rounded-3xl p-6 md:p-8 border border-gray-800 relative overflow-hidden">
                <div className="absolute top-0 right-0 -mt-10 -mr-10 w-40 h-40 bg-secondary/10 rounded-full blur-3xl pointer-events-none" />
                <form onSubmit={handleSubmit} className="space-y-5 relative z-10">
                    <div>
                        <label className="text-dimWhite font-poppins text-sm mb-1.5 block">Имя пользователя получателя</label>
                        <div className="relative">
                            <User className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                            <input type="text" name="recipientName" value={formData.recipientName} onChange={handleChange}
                                className={`w-full bg-primary/50 text-white border ${errors.recipientName ? 'border-red-500' : 'border-gray-700 focus:border-secondary'} rounded-xl pl-10 pr-4 py-3 font-poppins outline-none transition-colors`}
                                placeholder="например: ivanov123" />
                        </div>
                        {errors.recipientName && <p className="text-red-500 text-xs mt-1 flex items-center gap-1"><AlertCircle size={12} />{errors.recipientName}</p>}
                    </div>

                    <div>
                        <label className="text-dimWhite font-poppins text-sm mb-1.5 block">Номер счёта</label>
                        <div className="relative">
                            <Hash className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                            <input type="text" name="accountNumber" value={formData.accountNumber} onChange={handleChange}
                                className={`w-full bg-primary/50 text-white border ${errors.accountNumber ? 'border-red-500' : 'border-gray-700 focus:border-secondary'} rounded-xl pl-10 pr-4 py-3 font-poppins outline-none transition-colors`}
                                placeholder="0000 0000 0000" />
                        </div>
                        {errors.accountNumber && <p className="text-red-500 text-xs mt-1 flex items-center gap-1"><AlertCircle size={12} />{errors.accountNumber}</p>}
                    </div>

                    <div>
                        <label className="text-dimWhite font-poppins text-sm mb-1.5 block">Сумма (USD)</label>
                        <div className="relative">
                            <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                            <input type="number" name="amount" value={formData.amount} onChange={handleChange}
                                className={`w-full bg-primary/50 text-white border ${errors.amount ? 'border-red-500' : 'border-gray-700 focus:border-secondary'} rounded-xl pl-10 pr-4 py-3 text-2xl font-poppins outline-none transition-colors font-medium`}
                                placeholder="0.00" />
                        </div>
                        {errors.amount && <p className="text-red-500 text-xs mt-1 flex items-center gap-1"><AlertCircle size={12} />{errors.amount}</p>}
                        <div className="flex gap-2 mt-2">
                            {QUICK_AMOUNTS.map(q => (
                                <button key={q} type="button" onClick={() => setFormData(f => ({ ...f, amount: String(q) }))}
                                    className={`px-3 py-1 rounded-lg text-xs font-poppins border transition-all ${formData.amount === String(q) ? 'bg-secondary/20 text-secondary border-secondary/30' : 'bg-black/30 text-dimWhite border-gray-800 hover:border-gray-600'}`}>
                                    ${q}
                                </button>
                            ))}
                        </div>
                    </div>

                    <div>
                        <label className="text-dimWhite font-poppins text-sm mb-1.5 block">Комментарий (необязательно)</label>
                        <div className="relative">
                            <FileText className="absolute left-3 top-3.5 text-dimWhite" size={18} />
                            <textarea name="note" value={formData.note} onChange={handleChange}
                                className="w-full bg-primary/50 text-white border border-gray-700 focus:border-secondary rounded-xl pl-10 pr-4 py-3 font-poppins outline-none transition-colors resize-none h-20"
                                placeholder="За что перевод?" />
                        </div>
                    </div>

                    <button type="submit" disabled={loading}
                        className={`w-full flex items-center justify-center gap-3 bg-blue-gradient text-primary py-4 rounded-xl font-poppins font-semibold text-lg transition-all mt-2 ${loading ? 'opacity-80 cursor-wait' : 'hover:-translate-y-1 hover:shadow-[0_0_20px_rgba(51,187,207,0.4)]'}`}>
                        {loading ? <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" /> : <><Send size={20} /> Подтвердить перевод</>}
                    </button>
                </form>
            </div>
        </div>
    );
};

export default TransferMoney;
