import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';

/* ── FeedbackModal ───────────────────────────────────────────────── */
const CATEGORY_OPTIONS = [
    { value: 'bug',     label: 'Bug 🐛' },
    { value: 'feature', label: 'Feature-Wunsch ✨' },
    { value: 'idea',    label: 'Idee 💡' },
];

function FeedbackModal({ onClose }) {
    const [title, setTitle] = useState('');
    const [body, setBody] = useState('');
    const [category, setCategory] = useState('bug');
    const [loading, setLoading] = useState(false);
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!title.trim() || !body.trim()) { setError('Bitte Titel und Beschreibung ausfüllen.'); return; }
        setLoading(true);
        setError('');
        try {
            const token = localStorage.getItem('token');
            const API = process.env.REACT_APP_API_URL || '';
            const res = await fetch(`${API}/api/feedback`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
                body: JSON.stringify({ title, body, category })
            });
            const json = await res.json();
            if (json.status === 'success') { setSuccess(true); }
            else { setError('Fehler beim Senden.'); }
        } catch {
            setError('Server nicht erreichbar.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div
            onClick={onClose}
            style={{
                position: 'fixed', inset: 0, zIndex: 9999,
                background: 'rgba(0,0,0,0.55)',
                display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}
        >
            <div
                onClick={e => e.stopPropagation()}
                style={{
                    background: 'var(--card-bg, #1e1e2e)',
                    border: '1px solid var(--border-color, rgba(255,255,255,0.1))',
                    borderRadius: 12,
                    padding: 28,
                    width: '100%',
                    maxWidth: 440,
                    boxShadow: '0 20px 60px rgba(0,0,0,0.5)'
                }}
            >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
                    <h2 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: 'var(--text-primary, #f1f5f9)' }}>
                        Feedback senden
                    </h2>
                    <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, color: 'var(--text-muted, #64748b)', lineHeight: 1 }}>×</button>
                </div>

                {success ? (
                    <div style={{ textAlign: 'center', padding: '24px 0' }}>
                        <div style={{ fontSize: 36, marginBottom: 12 }}>✅</div>
                        <p style={{ color: 'var(--text-primary, #f1f5f9)', fontWeight: 600, marginBottom: 6 }}>Feedback gesendet!</p>
                        <p style={{ color: 'var(--text-secondary, #94a3b8)', fontSize: 13 }}>Das Issue wurde auf GitHub erstellt.</p>
                        <button onClick={onClose} style={{ marginTop: 16, padding: '8px 20px', borderRadius: 8, border: 'none', background: 'var(--accent, #6366f1)', color: '#fff', cursor: 'pointer', fontWeight: 600 }}>Schließen</button>
                    </div>
                ) : (
                    <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                        <div>
                            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary, #94a3b8)', display: 'block', marginBottom: 6 }}>Kategorie</label>
                            <select
                                value={category}
                                onChange={e => setCategory(e.target.value)}
                                style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-color, rgba(255,255,255,0.1))', background: 'var(--input-bg, #252535)', color: 'var(--text-primary, #f1f5f9)', fontSize: 13 }}
                            >
                                {CATEGORY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                            </select>
                        </div>
                        <div>
                            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary, #94a3b8)', display: 'block', marginBottom: 6 }}>Titel</label>
                            <input
                                type="text"
                                value={title}
                                onChange={e => setTitle(e.target.value)}
                                placeholder="Kurze Zusammenfassung…"
                                style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-color, rgba(255,255,255,0.1))', background: 'var(--input-bg, #252535)', color: 'var(--text-primary, #f1f5f9)', fontSize: 13, boxSizing: 'border-box' }}
                            />
                        </div>
                        <div>
                            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary, #94a3b8)', display: 'block', marginBottom: 6 }}>Beschreibung</label>
                            <textarea
                                value={body}
                                onChange={e => setBody(e.target.value)}
                                placeholder="Was ist passiert? Was hast du erwartet?"
                                rows={5}
                                style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-color, rgba(255,255,255,0.1))', background: 'var(--input-bg, #252535)', color: 'var(--text-primary, #f1f5f9)', fontSize: 13, resize: 'vertical', boxSizing: 'border-box', fontFamily: 'inherit' }}
                            />
                        </div>
                        {error && <p style={{ color: '#ef4444', fontSize: 12, margin: 0 }}>{error}</p>}
                        <button
                            type="submit"
                            disabled={loading}
                            style={{ padding: '9px 0', borderRadius: 8, border: 'none', background: 'var(--accent, #6366f1)', color: '#fff', fontWeight: 600, fontSize: 14, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}
                        >
                            {loading ? 'Senden…' : 'Feedback senden'}
                        </button>
                    </form>
                )}
            </div>
        </div>
    );
}

/* ── SVG Icon Components ────────────────────────────────────────── */
const I = ({ d, children, ...p }) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" {...p}>
        {d ? <path d={d} /> : children}
    </svg>
);

const icons = {
    dashboard:   <I><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></I>,
    portal:      <I d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>,
    tickets:     <I><path d="M22 12c0-5.5-4.5-10-10-10S2 6.5 2 12v6a2 2 0 0 0 2 2h2v-7H4v-1a8 8 0 0 1 16 0v1h-2v7h2a2 2 0 0 0 2-2z"/></I>,
    knowledge:   <I><path d="M4 4.5A2.5 2.5 0 0 1 6.5 2H20v17H6.5a2.5 2.5 0 0 0 0 5H20"/><path d="M8 7h8M8 11h6"/></I>,
    anleitungen: <I><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M9 13h6M9 17h4"/></I>,
    assets:      <I><rect x="2" y="7" width="20" height="13" rx="2"/><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></I>,
    warehouse:   <I><path d="m21 16-9 5-9-5V8l9-5 9 5z"/><path d="m3 8 9 5 9-5M12 13v8"/></I>,
    licenses:    <I><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></I>,
    maintenance: <I d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>,
    fido:        <I d="m15.5 7.5 3 3L22 7l-3-3M21 2l-9.6 9.6a5.5 5.5 0 1 1-2 2L19 4"/>,
    lifecycle:   <I><path d="M21 12a9 9 0 1 1-9-9c2.5 0 4.78 1 6.43 2.57L21 8"/><path d="M21 3v5h-5"/></I>,
    anlagevermoegen: <I><path d="M3 21h18M5 11v6M9 11v6M15 11v6M19 11v6M3 7l9-4 9 4v3H3z"/></I>,
    monitoring:  <I d="M22 12h-4l-3 9L9 3l-3 9H2"/>,
    defender:    <I d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>,
    patch:       <I><path d="M12 8V4M12 4l-3 3M12 4l3 3M3 12h4M3 12l3-3M3 12l3 3M12 16v4M12 20l-3-3M12 20l3-3M21 12h-4M21 12l-3-3M21 12l-3 3"/></I>,
    compliance:  <I><path d="M9 12l2 2 4-4M21 12c0 5-3.5 9-9 9s-9-4-9-9V5l9-3 9 3z"/></I>,
    entra:       <I><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></I>,
    users:       <I><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></I>,
    security:    <I><path d="M12 2 4 5v6c0 5 3.5 8 8 11 4.5-3 8-6 8-11V5z"/><path d="M9 12l2 2 4-4"/></I>,
    ki:          <I><path d="M12 2a3 3 0 0 0-3 3v1H7a3 3 0 0 0-3 3v2H3a2 2 0 0 0 0 4h1v2a3 3 0 0 0 3 3h2v1a3 3 0 0 0 6 0v-1h2a3 3 0 0 0 3-3v-2h1a2 2 0 0 0 0-4h-1V9a3 3 0 0 0-3-3h-2V5a3 3 0 0 0-3-3z"/></I>,
    onboarding:  <I><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><path d="M20 8v6M23 11h-6"/></I>,
    announcements: <I><path d="M11 5L6 9H2v6h4l5 4V5zM19 12c0-2.5-1.5-5-4-6"/></I>,
    feedback:      <I><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></I>,
    system:      <I><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></I>,
};

/* ── NavItem ─────────────────────────────────────────────────────── */
const NavItem = ({ to, icon, label, badge, badgeCls, active }) => (
    <Link to={to} className={`sidebar-link${active ? ' sidebar-link--active' : ''}`}>
        <span className="sidebar-link-icon">{icons[icon] || icons.dashboard}</span>
        <span className="sidebar-link-label">{label}</span>
        {badge != null && <span className={`sidebar-badge${badgeCls ? ' ' + badgeCls : ''}`}>{badge}</span>}
    </Link>
);

/* ── Submenu ─────────────────────────────────────────────────────── */
const SubMenu = ({ label, icon, items, isActive }) => {
    const hasActive = items.some(i => isActive(i.to));
    const [open, setOpen] = useState(hasActive);
    return (
        <>
            <button className={`sidebar-link${hasActive ? ' sidebar-link--active' : ''}`} onClick={() => setOpen(o => !o)}>
                <span className="sidebar-link-icon">{icons[icon] || icons.compliance}</span>
                <span className="sidebar-link-label">{label}</span>
                <span className={`sidebar-submenu-chevron${open ? ' open' : ''}`}>▸</span>
            </button>
            {open && (
                <div className="sidebar-submenu">
                    {items.map(item => (
                        <Link key={item.to} to={item.to} className={`sidebar-link${isActive(item.to) ? ' sidebar-link--active' : ''}`} style={{ fontSize: 13 }}>
                            <span className="sidebar-link-icon">{icons[item.icon] || icons.dashboard}</span>
                            <span className="sidebar-link-label">{item.label}</span>
                        </Link>
                    ))}
                </div>
            )}
        </>
    );
};

/* ═══════════════════════════════════════════════════════════════════
   Sidebar
═══════════════════════════════════════════════════════════════════ */
const Sidebar = () => {
    const location = useLocation();
    const { user, isAdmin, isSupport, isTechniker, canViewLifecycle, canModifyFidoKeys } = useAuth();
    const [feedbackOpen, setFeedbackOpen] = useState(false);

    const isStaff = isSupport();
    const role = user?.role_name;

    const isActive = (to) => {
        if (to === '/dashboard' || to === '/portal') return location.pathname === to;
        return location.pathname.startsWith(to);
    };

    return (
        <aside className="sidebar">
            {/* Brand */}
            <Link to={isStaff ? '/dashboard' : '/portal'} className="sidebar-brand">
                <div className="sidebar-brand-mark">C</div>
                <div>
                    <div className="sidebar-brand-name">Cereda Systems</div>
                    <div className="sidebar-brand-sub">IT Nexus</div>
                </div>
            </Link>

            {/* Nav Search */}
            <div className="sidebar-search">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" width="14" height="14" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>
                </svg>
                <span>Suchen…</span>
                <span className="sidebar-search-kbd">⌘K</span>
            </div>

            <nav className="sidebar-nav">
                {/* Dashboard / Portal */}
                <div className="sidebar-group">
                    {isStaff && <NavItem to="/dashboard" icon="dashboard" label="Dashboard" active={isActive('/dashboard')} />}
                    {!isStaff && <NavItem to="/portal" icon="portal" label="Mein Portal" active={isActive('/portal')} />}
                </div>

                {/* Helpdesk */}
                <div className="sidebar-group">
                    <div className="sidebar-group-label">Helpdesk</div>
                    {isStaff && <NavItem to="/tickets" icon="tickets" label="Tickets" active={isActive('/tickets')} />}
                    {isStaff && <NavItem to="/knowledge-base" icon="knowledge" label="Wissensdatenbank" active={isActive('/knowledge-base')} />}
                    <NavItem to="/anleitungen" icon="anleitungen" label="Anleitungen" active={isActive('/anleitungen')} />
                </div>

                {/* IT-Verwaltung */}
                {(isStaff || isTechniker() || canModifyFidoKeys() || canViewLifecycle() || ['admin','super_admin','buchhaltung'].includes(role)) && (
                    <div className="sidebar-group">
                        <div className="sidebar-group-label">IT-Verwaltung</div>
                        {(isStaff || isTechniker()) && <NavItem to="/assets" icon="assets" label="Assets" active={isActive('/assets')} />}
                        {isStaff && <NavItem to="/warehouse" icon="warehouse" label="Lager" active={isActive('/warehouse')} />}
                        {canModifyFidoKeys() && <NavItem to="/licenses" icon="licenses" label="Lizenzen" active={isActive('/licenses')} />}
                        {canModifyFidoKeys() && <NavItem to="/maintenance" icon="maintenance" label="Wartung" active={isActive('/maintenance')} />}
                        {isStaff && <NavItem to="/fido-keys" icon="fido" label="FIDO-Keys" active={isActive('/fido-keys')} />}
                        {canViewLifecycle() && <NavItem to="/lifecycle" icon="lifecycle" label="Lifecycle" active={isActive('/lifecycle')} />}
                        {['admin','super_admin','buchhaltung'].includes(role) && <NavItem to="/anlagevermoegen" icon="anlagevermoegen" label="Anlagevermögen" active={isActive('/anlagevermoegen')} />}
                    </div>
                )}

                {/* Monitoring & Security */}
                {isAdmin() && (
                    <div className="sidebar-group">
                        <div className="sidebar-group-label">Monitoring & Security</div>
                        <NavItem to="/monitoring" icon="monitoring" label="Monitoring" active={isActive('/monitoring')} />
                        <NavItem to="/nexus-scanner" icon="monitoring" label="Nexus Scanner" badge="NEU" badgeCls="accent" active={isActive('/nexus-scanner')} />
                        <NavItem to="/defender" icon="defender" label="Microsoft Defender" active={isActive('/defender')} />
                        <NavItem to="/patch-management" icon="patch" label="Patch Management" active={isActive('/patch-management')} />
                        <SubMenu label="Compliance" icon="compliance" isActive={isActive} items={[
                            { to: '/it-overview', label: 'IT Übersicht',       icon: 'dashboard' },
                            { to: '/iso',         label: 'ISO-Zertifizierung', icon: 'compliance' },
                            { to: '/risk',        label: 'Risikoanalyse',      icon: 'security' },
                        ]} />
                    </div>
                )}

                {/* Administration */}
                {isAdmin() && (
                    <div className="sidebar-group">
                        <div className="sidebar-group-label">Administration</div>
                        <NavItem to="/benutzerverwaltung" icon="users" label="Benutzerverwaltung" badge="NEU" badgeCls="accent" active={isActive('/benutzerverwaltung')} />
                        <NavItem to="/entra" icon="entra" label="Entra Rechte" active={isActive('/entra')} />
                        <NavItem to="/users" icon="users" label="Benutzer" active={isActive('/users')} />
                        <NavItem to="/announcements" icon="announcements" label="Ankündigungen" active={isActive('/announcements')} />
                        <NavItem to="/security-reports" icon="security" label="Security Reports" active={isActive('/security-reports')} />
                        <NavItem to="/ki-wissen" icon="ki" label="KI Wissensdatenbank" badge="NEU" badgeCls="accent" active={isActive('/ki-wissen')} />
                        <NavItem to="/proxmox" icon="monitoring" label="Proxmox" active={isActive('/proxmox')} />
                        <NavItem to="/docker" icon="monitoring" label="Docker" active={isActive('/docker')} />
                        <NavItem to="/system" icon="system" label="Systemeinstellungen" active={isActive('/system')} />
                        <NavItem to="/feedback" icon="feedback" label="Feedback Issues" active={isActive('/feedback')} />
                    </div>
                )}
            </nav>

            {/* Feedback Button */}
            <div style={{ padding: '12px 12px 16px' }}>
                <button
                    onClick={() => setFeedbackOpen(true)}
                    style={{
                        width: '100%',
                        padding: '9px 14px',
                        borderRadius: 8,
                        border: '1px solid var(--border-color, rgba(255,255,255,0.08))',
                        background: 'transparent',
                        color: 'var(--text-secondary, #94a3b8)',
                        fontSize: 13,
                        fontWeight: 500,
                        cursor: 'pointer',
                        display: 'flex',
                        alignItems: 'center',
                        gap: 8,
                        transition: 'background .15s'
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.04)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                >
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" width="16" height="16">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    </svg>
                    Feedback geben
                </button>
            </div>

            {feedbackOpen && <FeedbackModal onClose={() => setFeedbackOpen(false)} />}
        </aside>
    );
};

export default Sidebar;
