import { useState, useEffect } from 'react';
import { StickyNote, Plus, X, Edit2, Trash2, Check } from 'lucide-react';
import { fetchNotes, createNote, updateNote, deleteNote } from '../../api/mockApi';
import toast from 'react-hot-toast';

const NOTE_COLORS = [
    { id: 'blue', bg: 'from-blue-500/20 to-blue-600/10', border: 'border-blue-500/30', accent: 'bg-blue-500' },
    { id: 'purple', bg: 'from-purple-500/20 to-purple-600/10', border: 'border-purple-500/30', accent: 'bg-purple-500' },
    { id: 'green', bg: 'from-green-500/20 to-green-600/10', border: 'border-green-500/30', accent: 'bg-green-500' },
    { id: 'yellow', bg: 'from-yellow-500/20 to-yellow-600/10', border: 'border-yellow-500/30', accent: 'bg-yellow-500' },
    { id: 'red', bg: 'from-red-500/20 to-red-600/10', border: 'border-red-500/30', accent: 'bg-red-500' },
    { id: 'pink', bg: 'from-pink-500/20 to-pink-600/10', border: 'border-pink-500/30', accent: 'bg-pink-500' },
];

const getColorCfg = (id) => NOTE_COLORS.find(c => c.id === id) || NOTE_COLORS[0];

const NoteCard = ({ note, onEdit, onDelete }) => {
    const cfg = getColorCfg(note.color);
    return (
        <div className={`relative bg-gradient-to-br ${cfg.bg} border ${cfg.border} rounded-2xl p-5 flex flex-col gap-3 group`}>
            <div className={`absolute top-0 left-4 w-8 h-1 rounded-b-full ${cfg.accent}`} />
            <div className="flex items-start justify-between gap-2">
                <h4 className="text-white font-poppins font-semibold text-sm leading-snug">{note.title}</h4>
                <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
                    <button onClick={() => onEdit(note)} className="text-dimWhite hover:text-white"><Edit2 size={13} /></button>
                    <button onClick={() => onDelete(note.id)} className="text-dimWhite hover:text-red-400"><Trash2 size={13} /></button>
                </div>
            </div>
            <p className="text-dimWhite text-sm font-poppins leading-relaxed">{note.content}</p>
            <div className="text-dimWhite/50 text-xs font-poppins mt-auto">{new Date(note.updated_at).toLocaleString('ru-RU')}</div>
        </div>
    );
};

const AdminNotes = () => {
    const [notes, setNotes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editing, setEditing] = useState(null);
    const [form, setForm] = useState({ title: '', content: '', color: 'blue' });
    const [saving, setSaving] = useState(false);

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

    const loadNotes = async () => {
        setLoading(true);
        try { setNotes(await fetchNotes()); }
        catch { toast.error('Не удалось загрузить заметки'); }
        finally { setLoading(false); }
    };

    const openCreate = () => { setEditing(null); setForm({ title: '', content: '', color: 'blue' }); setIsModalOpen(true); };
    const openEdit = (note) => { setEditing(note); setForm({ title: note.title, content: note.content, color: note.color }); setIsModalOpen(true); };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            if (editing) { await updateNote({ id: editing.id, ...form }); toast.success('Заметка обновлена!'); }
            else { await createNote(form); toast.success('Заметка создана!'); }
            setIsModalOpen(false);
            loadNotes();
        } catch (e) { toast.error(e.message || 'Ошибка'); }
        finally { setSaving(false); }
    };

    const handleDelete = async (id) => {
        try { await deleteNote(id); toast.success('Заметка удалена'); setNotes(notes.filter(n => n.id !== id)); }
        catch (e) { toast.error(e.message || 'Ошибка'); }
    };

    return (
        <div className="animate-fade-in pb-20">
            <div className="flex justify-between items-center mb-8">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Заметки</h2>
                    <p className="text-dimWhite font-poppins text-sm">Личные заметки администратора</p>
                </div>
                <button onClick={openCreate} className="flex items-center gap-2 bg-blue-gradient text-primary px-5 py-2.5 rounded-xl font-poppins font-medium hover:opacity-90">
                    <Plus size={18} /> Новая заметка
                </button>
            </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>
            ) : notes.length === 0 ? (
                <div className="bg-black-gradient-2 rounded-2xl p-10 text-center border border-gray-800">
                    <StickyNote className="mx-auto text-dimWhite mb-4" size={44} />
                    <h3 className="text-xl font-poppins text-white mb-2">Заметок нет</h3>
                    <button onClick={openCreate} className="bg-secondary/20 text-secondary hover:bg-secondary/30 px-6 py-2 rounded-lg font-poppins mt-2">Создать заметку</button>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {notes.map(note => <NoteCard key={note.id} note={note} onEdit={openEdit} onDelete={handleDelete} />)}
                </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-md 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-purple-500" />
                        <div className="flex justify-between items-center mb-5">
                            <h3 className="text-xl font-poppins font-semibold text-white">{editing ? 'Редактировать' : 'Новая заметка'}</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-white"><X size={22} /></button>
                        </div>
                        <form onSubmit={handleSave} className="space-y-4">
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Заголовок</label>
                                <input type="text" value={form.title} onChange={(e) => setForm(f => ({ ...f, title: e.target.value }))} required
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="Заголовок заметки..." />
                            </div>
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Текст</label>
                                <textarea value={form.content} onChange={(e) => setForm(f => ({ ...f, content: e.target.value }))} required
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary h-28 resize-none" placeholder="Содержание заметки..." />
                            </div>
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Цвет</label>
                                <div className="flex gap-2">
                                    {NOTE_COLORS.map(c => (
                                        <button key={c.id} type="button" onClick={() => setForm(f => ({ ...f, color: c.id }))}
                                            className={`w-7 h-7 rounded-full ${c.accent} transition-transform flex items-center justify-center ${form.color === c.id ? 'scale-125 ring-2 ring-white/40' : 'opacity-60 hover:opacity-100'}`}>
                                            {form.color === c.id && <Check size={10} className="text-white" />}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            <button type="submit" disabled={saving}
                                className={`w-full py-3 rounded-xl font-poppins font-semibold ${saving ? 'bg-gray-600 text-gray-300' : 'bg-blue-gradient text-primary hover:opacity-90'}`}>
                                {saving ? 'Сохранение...' : (editing ? 'Обновить' : 'Создать')}
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminNotes;
