import React, { useState, useEffect, useCallback } from 'react';
import api from '../services/api';
import { toast } from 'react-toastify';
import { useAuth } from '../context/AuthContext';

const CATEGORIES = ['Infrastruktur', 'IT Nexus', 'Agent', 'Proxmox', 'Sicherheit', 'Projekte', 'Zugänge', 'Erkenntnisse', 'Allgemein'];

const CAT_ICONS = {
    'Infrastruktur': '🏢', 'IT Nexus': '🚀', 'Agent': '🤖', 'Proxmox': '🖥️',
    'Sicherheit': '🔒', 'Projekte': '📋', 'Zugänge': '🔑', 'Erkenntnisse': '💡', 'Allgemein': '📝',
};

const EntryModal = ({ initial, onSave, onClose }) => {
    const [form, setForm] = useState(initial || { title: '', content: '', category: 'Allgemein', tags: [] });
    const [tag, setTag] = useState('');

    const addTag = () => { if (tag.trim()) { setForm(f => ({ ...f, tags: [...f.tags, tag.trim()] })); setTag(''); } };

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}
            onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
            <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 14, padding: 28, width: 660, maxWidth: '90vw', maxHeight: '85vh', overflow: 'auto', boxShadow: '0 25px 60px rgba(0,0,0,0.5)' }}>
                <h3 style={{ margin: '0 0 20px', fontSize: 16 }}>{form.id ? 'Eintrag bearbeiten' : 'Neuer Eintrag'}</h3>

                <div style={{ display: 'flex', gap: 12, marginBottom: 14 }}>
                    <div style={{ flex: 1 }}>
                        <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>Titel *</label>
                        <input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                            style={{ width: '100%', padding: '9px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 13, boxSizing: 'border-box' }} />
                    </div>
                    <div>
                        <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>Kategorie</label>
                        <select value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))}
                            style={{ padding: '9px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 13 }}>
                            {CATEGORIES.map(c => <option key={c}>{c}</option>)}
                        </select>
                    </div>
                </div>

                <div style={{ marginBottom: 14 }}>
                    <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>Inhalt * (Markdown unterstützt)</label>
                    <textarea value={form.content} onChange={e => setForm(f => ({ ...f, content: e.target.value }))}
                        rows={12} style={{ width: '100%', padding: '9px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 12, fontFamily: 'monospace', resize: 'vertical', boxSizing: 'border-box' }} />
                </div>

                <div style={{ marginBottom: 20 }}>
                    <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>Tags</label>
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
                        {form.tags.map((t, i) => (
                            <span key={i} style={{ padding: '3px 10px', borderRadius: 10, background: 'rgba(99,102,241,0.15)', color: '#818cf8', border: '1px solid #6366f140', fontSize: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
                                {t} <button onClick={() => setForm(f => ({ ...f, tags: f.tags.filter((_, j) => j !== i) }))} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#818cf8', fontSize: 14, padding: 0 }}>×</button>
                            </span>
                        ))}
                    </div>
                    <div style={{ display: 'flex', gap: 8 }}>
                        <input value={tag} onChange={e => setTag(e.target.value)} onKeyDown={e => e.key === 'Enter' && addTag()}
                            placeholder="Tag eingeben + Enter" style={{ flex: 1, padding: '7px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 12 }} />
                        <button onClick={addTag} style={{ padding: '7px 14px', borderRadius: 8, border: '1px solid var(--accent)', background: 'rgba(99,102,241,0.1)', color: 'var(--accent)', cursor: 'pointer', fontSize: 12 }}>+</button>
                    </div>
                </div>

                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                    <button onClick={onClose} style={{ padding: '9px 20px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-secondary)', cursor: 'pointer', fontSize: 13 }}>Abbrechen</button>
                    <button onClick={() => onSave(form)} style={{ padding: '9px 24px', borderRadius: 8, border: 'none', background: 'linear-gradient(135deg, #6366f1, #818cf8)', color: '#fff', cursor: 'pointer', fontSize: 13, fontWeight: 700 }}>Speichern</button>
                </div>
            </div>
        </div>
    );
};

export default function KnowledgeAiPage() {
    const { isAdmin } = useAuth();
    const [entries, setEntries] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [activeCategory, setActiveCategory] = useState('Alle');
    const [expanded, setExpanded] = useState({});
    const [modal, setModal] = useState(null);

    const load = useCallback(async () => {
        try {
            const data = await api.get('/knowledge').then(r => r.data);
            setEntries(data);
        } catch { toast.error('Fehler beim Laden'); }
        setLoading(false);
    }, []);

    useEffect(() => {
        load();
        const interval = setInterval(load, 30000);
        return () => clearInterval(interval);
    }, [load]);

    const save = async (form) => {
        try {
            if (form.id) await api.put(`/knowledge/${form.id}`, form);
            else await api.post('/knowledge', form);
            toast.success('Gespeichert');
            setModal(null);
            load();
        } catch { toast.error('Fehler'); }
    };

    const remove = async (id) => {
        if (!window.confirm('Eintrag löschen?')) return;
        try { await api.delete(`/knowledge/${id}`); load(); } catch { toast.error('Fehler'); }
    };

    const filtered = entries.filter(e => {
        const matchCat = activeCategory === 'Alle' || e.category === activeCategory;
        const matchSearch = !search || e.title.toLowerCase().includes(search.toLowerCase()) || e.content.toLowerCase().includes(search.toLowerCase());
        return matchCat && matchSearch;
    });

    const grouped = {};
    filtered.forEach(e => { if (!grouped[e.category]) grouped[e.category] = []; grouped[e.category].push(e); });

    const cats = ['Alle', ...CATEGORIES.filter(c => entries.some(e => e.category === c))];

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Laden...</div>;

    return (
        <div style={{ padding: 28 }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24 }}>
                <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
                        <h1 style={{ margin: 0, fontSize: 24, fontWeight: 800 }}>KI Wissendatenbank</h1>
                        <span style={{ fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 10, background: 'linear-gradient(135deg, #6366f120, #818cf820)', color: '#818cf8', border: '1px solid #6366f140' }}>
                            🤖 Claude liest das automatisch
                        </span>
                    </div>
                    <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 13 }}>
                        Alles was ich wissen muss — Infrastruktur, Projekte, Erkenntnisse. Wird bei jeder Session automatisch geladen.
                    </p>
                </div>
                {isAdmin() && (
                    <button className="btn btn-primary" onClick={() => setModal({ title: '', content: '', category: 'Allgemein', tags: [] })}>
                        + Neuer Eintrag
                    </button>
                )}
            </div>

            {/* Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10, marginBottom: 24 }}>
                {CATEGORIES.filter(c => entries.some(e => e.category === c)).map(c => (
                    <div key={c} onClick={() => setActiveCategory(activeCategory === c ? 'Alle' : c)}
                        style={{ background: activeCategory === c ? 'rgba(99,102,241,0.15)' : 'var(--bg-card)', border: `1px solid ${activeCategory === c ? '#6366f1' : 'var(--border-color)'}`, borderRadius: 10, padding: '10px 14px', cursor: 'pointer', transition: 'all .2s' }}>
                        <div style={{ fontSize: 18, marginBottom: 4 }}>{CAT_ICONS[c]}</div>
                        <div style={{ fontSize: 12, fontWeight: 700 }}>{c}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{entries.filter(e => e.category === c).length} Einträge</div>
                    </div>
                ))}
            </div>

            {/* Suche + Filter */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 24, alignItems: 'center' }}>
                <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Suchen..."
                    style={{ flex: 1, padding: '9px 14px', borderRadius: 10, border: '1px solid var(--border-color)', background: 'var(--bg-card)', color: 'var(--text-primary)', fontSize: 13 }} />
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {cats.map(c => (
                        <button key={c} onClick={() => setActiveCategory(c)}
                            style={{ padding: '6px 14px', borderRadius: 8, border: `1px solid ${activeCategory === c ? '#6366f1' : 'var(--border-color)'}`, background: activeCategory === c ? 'rgba(99,102,241,0.15)' : 'none', color: activeCategory === c ? '#818cf8' : 'var(--text-muted)', cursor: 'pointer', fontSize: 12, fontWeight: activeCategory === c ? 700 : 400 }}>
                            {c === 'Alle' ? `Alle (${entries.length})` : `${CAT_ICONS[c]} ${c}`}
                        </button>
                    ))}
                </div>
            </div>

            {/* Einträge */}
            {filtered.length === 0 && (
                <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--text-muted)' }}>
                    <div style={{ fontSize: 40, marginBottom: 12 }}>🤖</div>
                    <div style={{ fontSize: 14 }}>Noch keine Einträge. Leg los!</div>
                </div>
            )}

            {Object.entries(grouped).map(([cat, items]) => (
                <div key={cat} style={{ marginBottom: 28 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                        <span style={{ fontSize: 18 }}>{CAT_ICONS[cat]}</span>
                        <span style={{ fontWeight: 700, fontSize: 15 }}>{cat}</span>
                        <span style={{ fontSize: 11, color: 'var(--text-muted)', background: 'var(--bg-secondary)', padding: '2px 8px', borderRadius: 8 }}>{items.length}</span>
                    </div>

                    {items.map(e => {
                        const isOpen = expanded[e.id];
                        const tags = JSON.parse(e.tags || '[]');
                        return (
                            <div key={e.id} style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 10, marginBottom: 8, overflow: 'hidden' }}>
                                {/* Titel-Zeile */}
                                <div onClick={() => setExpanded(p => ({ ...p, [e.id]: !p[e.id] }))}
                                    style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', cursor: 'pointer', userSelect: 'none' }}>
                                    <span style={{ color: 'var(--text-muted)', fontSize: 12, transition: 'transform .2s', transform: isOpen ? 'rotate(90deg)' : 'none' }}>▶</span>
                                    <span style={{ fontWeight: 600, fontSize: 14, flex: 1 }}>{e.title}</span>
                                    {tags.map((t, i) => (
                                        <span key={i} style={{ fontSize: 10, padding: '2px 8px', borderRadius: 8, background: 'rgba(99,102,241,0.1)', color: '#818cf8', border: '1px solid #6366f130' }}>{t}</span>
                                    ))}
                                    <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                                        {new Date(e.updated_at).toLocaleDateString('de-DE')}
                                    </span>
                                    {isAdmin() && (
                                        <div style={{ display: 'flex', gap: 6 }} onClick={ev => ev.stopPropagation()}>
                                            <button onClick={() => setModal({ ...e, tags: JSON.parse(e.tags || '[]') })}
                                                style={{ padding: '3px 8px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 11 }}>✏️</button>
                                            <button onClick={() => remove(e.id)}
                                                style={{ padding: '3px 8px', borderRadius: 6, border: '1px solid rgba(239,68,68,0.3)', background: 'rgba(239,68,68,0.1)', color: '#ef4444', cursor: 'pointer', fontSize: 11 }}>🗑</button>
                                        </div>
                                    )}
                                </div>

                                {/* Inhalt */}
                                {isOpen && (
                                    <div style={{ borderTop: '1px solid var(--border-color)', padding: '16px 20px', background: 'var(--bg-secondary)' }}>
                                        <pre style={{ margin: 0, fontFamily: 'inherit', fontSize: 13, color: 'var(--text-secondary)', whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>{e.content}</pre>
                                        <div style={{ marginTop: 12, fontSize: 11, color: 'var(--text-muted)' }}>
                                            Erstellt von <strong>{e.author_name || 'System'}</strong> · Aktualisiert {new Date(e.updated_at).toLocaleString('de-DE')}
                                        </div>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            ))}

            {modal && <EntryModal initial={modal} onSave={save} onClose={() => setModal(null)} />}
        </div>
    );
}
