import { useState } from 'react';
import { User, Mail, Phone, MapPin, CreditCard, Shield, Edit3, Save, X } from 'lucide-react';
import toast from 'react-hot-toast';

const InfoRow = ({ icon: Icon, label, value, placeholder }) => (
    <div className="flex items-start gap-4 py-4 border-b border-gray-800/60 last:border-0">
        <div className="w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center flex-shrink-0 mt-0.5">
            <Icon size={16} className="text-secondary" />
        </div>
        <div className="flex-1 min-w-0">
            <p className="text-dimWhite text-xs font-poppins uppercase tracking-wider mb-0.5">{label}</p>
            <p className="text-white font-poppins font-medium text-sm break-all">
                {value || <span className="text-dimWhite/40 italic">{placeholder || 'Не указано'}</span>}
            </p>
        </div>
    </div>
);

const ProfileView = () => {
    const userStr = localStorage.getItem('iosco_user');
    const user = userStr ? JSON.parse(userStr) : {};

    const [editing, setEditing] = useState(false);
    const [form, setForm] = useState({
        full_name:   user.full_name   || '',
        phone:       user.phone       || '',
        postal_code: user.postal_code || '',
        email:       user.email       || '',
    });

    const handleSave = () => {
        const updated = { ...user, ...form };
        localStorage.setItem('iosco_user', JSON.stringify(updated));
        toast.success('Профиль обновлён локально');
        setEditing(false);
    };

    const inputCls = "w-full bg-black/40 border border-gray-700 focus:border-secondary rounded-xl px-4 py-2.5 text-white font-poppins text-sm outline-none transition-colors";

    const avatar = (user.full_name || user.username || '?')[0].toUpperCase();

    return (
        <div className="animate-fade-in pb-28 md:pb-10 max-w-xl">
            <h2 className="text-3xl font-poppins font-semibold text-white mb-8">Профиль</h2>

            {/* Avatar block */}
            <div className="flex items-center gap-5 mb-8 p-6 bg-black-gradient-2 rounded-2xl border border-gray-800">
                <div className="w-20 h-20 rounded-2xl bg-blue-gradient flex items-center justify-center text-primary font-poppins font-bold text-3xl flex-shrink-0 shadow-lg shadow-cyan-500/20">
                    {avatar}
                </div>
                <div>
                    <h3 className="text-white font-poppins font-bold text-xl">{user.full_name || user.username}</h3>
                    <p className="text-dimWhite font-poppins text-sm mt-0.5">{user.email}</p>
                    <span className={`inline-block mt-2 px-3 py-0.5 rounded-full text-xs font-poppins font-semibold ${user.role === 'admin' ? 'bg-yellow-500/15 text-yellow-400' : 'bg-secondary/15 text-secondary'}`}>
                        {user.role === 'admin' ? 'Администратор' : 'Клиент'}
                    </span>
                </div>
            </div>

            {/* Info / Edit */}
            <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden mb-6">
                <div className="flex items-center justify-between px-6 py-4 border-b border-gray-800">
                    <h3 className="text-white font-poppins font-semibold">Личные данные</h3>
                    {!editing ? (
                        <button onClick={() => setEditing(true)}
                            className="flex items-center gap-1.5 text-secondary text-sm font-poppins hover:underline">
                            <Edit3 size={13} /> Изменить
                        </button>
                    ) : (
                        <div className="flex items-center gap-3">
                            <button onClick={handleSave}
                                className="flex items-center gap-1.5 text-green-400 text-sm font-poppins hover:underline">
                                <Save size={13} /> Сохранить
                            </button>
                            <button onClick={() => setEditing(false)} className="text-dimWhite hover:text-white">
                                <X size={16} />
                            </button>
                        </div>
                    )}
                </div>

                <div className="px-6">
                    {editing ? (
                        <div className="py-5 space-y-4">
                            <div>
                                <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-1.5">ФИО</label>
                                <input className={inputCls} value={form.full_name} onChange={e => setForm(f => ({...f, full_name: e.target.value}))} placeholder="Иванов Иван Иванович" />
                            </div>
                            <div>
                                <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-1.5">Email</label>
                                <input className={inputCls} type="email" value={form.email} onChange={e => setForm(f => ({...f, email: e.target.value}))} placeholder="ivan@example.com" />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-1.5">Телефон</label>
                                    <input className={inputCls} type="tel" value={form.phone} onChange={e => setForm(f => ({...f, phone: e.target.value}))} placeholder="+7 999 000 00 00" />
                                </div>
                                <div>
                                    <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-1.5">Индекс</label>
                                    <input className={inputCls} value={form.postal_code} onChange={e => setForm(f => ({...f, postal_code: e.target.value}))} placeholder="123456" />
                                </div>
                            </div>
                        </div>
                    ) : (
                        <>
                            <InfoRow icon={User}    label="ФИО"      value={user.full_name}   placeholder="Не указано" />
                            <InfoRow icon={Mail}    label="Email"    value={user.email}       placeholder="Не указано" />
                            <InfoRow icon={Phone}   label="Телефон"  value={user.phone}       placeholder="Не указан" />
                            <InfoRow icon={MapPin}  label="Индекс"   value={user.postal_code} placeholder="Не указан" />
                        </>
                    )}
                </div>
            </div>

            {/* Security block */}
            <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                <div className="px-6 py-4 border-b border-gray-800">
                    <h3 className="text-white font-poppins font-semibold">Безопасность</h3>
                </div>
                <div className="px-6">
                    <InfoRow icon={Shield} label="Роль" value={user.role === 'admin' ? 'Администратор' : 'Клиент'} />
                    <InfoRow icon={CreditCard} label="Имя пользователя" value={user.username} />
                </div>
            </div>
        </div>
    );
};

export default ProfileView;
