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

const LICENSE_TYPES = [
    { value: 'subscription', label: 'Abonnement' },
    { value: 'oem', label: 'OEM' },
    { value: 'volume', label: 'Volumenlizenz' },
    { value: 'perpetual', label: 'Dauerlizenz' },
];

const TYPE_META = {
    subscription: { label: 'Abonnement', color: '#0ea5e9', bg: 'rgba(14,165,233,0.12)' },
    oem:          { label: 'OEM',         color: '#a78bfa', bg: 'rgba(167,139,250,0.12)' },
    volume:       { label: 'Volumen',     color: '#34d399', bg: 'rgba(52,211,153,0.12)' },
    perpetual:    { label: 'Dauerlizenz', color: '#fb923c', bg: 'rgba(251,146,60,0.12)' },
};

const VENDOR_ICON = (vendor) => {
    if (!vendor) return '📦';
    const v = vendor.toLowerCase();
    if (v.includes('microsoft')) return '🪟';
    if (v.includes('adobe')) return '🅰️';
    if (v.includes('google')) return '🔍';
    if (v.includes('apple')) return '🍎';
    if (v.includes('cisco')) return '🔗';
    if (v.includes('vmware') || v.includes('broadcom')) return '☁️';
    return '📦';
};

const EMPTY_FORM = {
    name: '', vendor: '', license_type: 'subscription',
    product_key: '', seats: '', purchase_date: '', expiry_date: '', cost: '', notes: '',
};

const today = new Date().toISOString().slice(0, 10);
const in30  = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);

const getExpiryStatus = (d) => {
    if (!d) return null;
    if (d < today) return 'expired';
    if (d <= in30) return 'soon';
    return 'ok';
};

/* ── Formular-Sektion ───────────────────────────────────────── */
const Section = ({ title, children }) => (
    <div>
        <div style={{
            fontSize: '10.5px', fontWeight: 700, textTransform: 'uppercase',
            letterSpacing: '0.09em', color: 'var(--text-muted)',
            marginBottom: '10px', paddingBottom: '6px',
            borderBottom: '1px solid var(--border-color)',
        }}>{title}</div>
        {children}
    </div>
);

/* ── Typ-Badge ──────────────────────────────────────────────── */
const TypeBadge = ({ type }) => {
    const m = TYPE_META[type] || { label: type, color: '#94a3b8', bg: 'rgba(148,163,184,0.12)' };
    return (
        <span style={{
            display: 'inline-block', padding: '2px 10px', borderRadius: '20px',
            fontSize: '11.5px', fontWeight: 600, letterSpacing: '0.02em',
            color: m.color, background: m.bg, border: `1px solid ${m.color}33`,
        }}>
            {m.label}
        </span>
    );
};

/* ── Sitzplatz-Balken ───────────────────────────────────────── */
const SeatsDisplay = ({ seats, notes }) => {
    if (seats === null || seats === undefined) return <span style={{ color: 'var(--text-muted)' }}>∞</span>;
    const match = notes && notes.match(/Genutzt:\s*(\d+)\s*\/\s*\d+/);
    const used = match ? parseInt(match[1]) : null;
    const pct = used !== null ? Math.min(100, Math.round((used / seats) * 100)) : null;
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
            <span style={{ fontSize: '13px', fontWeight: 600 }}>
                {used !== null ? `${used} / ${seats}` : seats}
            </span>
            {pct !== null && (
                <div style={{ height: '4px', borderRadius: '2px', background: 'var(--border-color)', width: '60px' }}>
                    <div style={{
                        height: '100%', borderRadius: '2px', width: `${pct}%`,
                        background: pct >= 90 ? '#ef4444' : pct >= 70 ? '#f59e0b' : '#10b981',
                        transition: 'width 0.3s',
                    }} />
                </div>
            )}
        </div>
    );
};

const LicensesPage = () => {
    const { isAdmin } = useAuth();
    const canEdit = isAdmin();

    const [licenses, setLicenses]     = useState([]);
    const [loading, setLoading]       = useState(true);
    const [search, setSearch]         = useState('');
    const [filterType, setFilterType] = useState('');
    const [filterExpiry, setFilterExpiry] = useState('');

    const [showModal, setShowModal]         = useState(false);
    const [editingLicense, setEditingLicense] = useState(null);
    const [formData, setFormData]           = useState(EMPTY_FORM);
    const [saving, setSaving]               = useState(false);
    const [showKey, setShowKey]             = useState(false);

    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [deletingLicense, setDeletingLicense] = useState(null);
    const [entraLoading, setEntraLoading]       = useState(false);

    // User-list modal state
    const [showUsersModal, setShowUsersModal]   = useState(false);
    const [usersLicense, setUsersLicense]       = useState(null);
    const [usersData, setUsersData]             = useState([]);
    const [usersLoading, setUsersLoading]       = useState(false);
    const [usersSearch, setUsersSearch]         = useState('');
    const [usersStatusFilter, setUsersStatusFilter] = useState('');

    const loadLicenses = useCallback(async () => {
        try { setLicenses(await licenseService.getAll()); }
        catch { toast.error('Fehler beim Laden der Lizenzen'); }
        finally { setLoading(false); }
    }, []);

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

    const openCreate = () => { setEditingLicense(null); setFormData(EMPTY_FORM); setShowKey(false); setShowModal(true); };
    const openEdit = (l) => {
        setEditingLicense(l);
        setFormData({
            name: l.name || '', vendor: l.vendor || '', license_type: l.license_type || 'subscription',
            product_key: l.product_key || '',
            seats: l.seats !== null && l.seats !== undefined ? String(l.seats) : '',
            purchase_date: l.purchase_date || '', expiry_date: l.expiry_date || '',
            cost: l.cost !== null && l.cost !== undefined ? String(l.cost) : '',
            notes: l.notes || '',
        });
        setShowKey(false); setShowModal(true);
    };

    const openUsers = async (license) => {
        setUsersLicense(license);
        setUsersData([]);
        setUsersSearch('');
        setUsersStatusFilter('');
        setShowUsersModal(true);
        setUsersLoading(true);
        try {
            const data = await licenseService.getLicenseUsers(license.id);
            setUsersData(data);
        } catch (err) {
            toast.error(err.response?.data?.message || 'Benutzer konnten nicht geladen werden');
            setShowUsersModal(false);
        } finally {
            setUsersLoading(false);
        }
    };

    const set = (f) => (e) => setFormData(p => ({ ...p, [f]: e.target.value }));

    const handleSave = async (e) => {
        e.preventDefault();
        if (!formData.name.trim()) { toast.error('Name ist erforderlich'); return; }
        setSaving(true);
        try {
            if (editingLicense) { await licenseService.update(editingLicense.id, formData); toast.success('Lizenz aktualisiert'); }
            else { await licenseService.create(formData); toast.success('Lizenz erstellt'); }
            setShowModal(false); loadLicenses();
        } catch (err) { toast.error(err.response?.data?.message || 'Fehler beim Speichern'); }
        finally { setSaving(false); }
    };

    const handleDelete = async () => {
        try {
            await licenseService.delete(deletingLicense.id);
            toast.success('Lizenz gelöscht');
            setShowDeleteModal(false); setDeletingLicense(null); loadLicenses();
        } catch { toast.error('Fehler beim Löschen'); }
    };

    const handleEntraImport = async () => {
        setEntraLoading(true);
        try {
            const result = await licenseService.importFromEntra();
            const msg = [];
            if (result.imported > 0) msg.push(`${result.imported} neu importiert`);
            if (result.updated  > 0) msg.push(`${result.updated} aktualisiert`);
            if (result.skipped  > 0) msg.push(`${result.skipped} übersprungen`);
            if (result.imported > 0 || result.updated > 0) {
                toast.success(msg.join(' · '));
                loadLicenses();
            } else {
                toast.info(msg.join(' · ') || 'Keine Lizenzen gefunden');
            }
        } catch (err) { toast.error(err.response?.data?.message || 'Entra-Import fehlgeschlagen'); }
        finally { setEntraLoading(false); }
    };

    const filtered = licenses.filter((l) => {
        const q = search.toLowerCase();
        const matchSearch = !q || l.name.toLowerCase().includes(q) || (l.vendor || '').toLowerCase().includes(q);
        const matchType = !filterType || l.license_type === filterType;
        const s = getExpiryStatus(l.expiry_date);
        const matchExpiry = !filterExpiry ||
            (filterExpiry === 'expired' && s === 'expired') ||
            (filterExpiry === 'soon'    && s === 'soon')    ||
            (filterExpiry === 'ok'      && (s === 'ok' || s === null));
        return matchSearch && matchType && matchExpiry;
    });

    const filteredUsers = usersData.filter((u) => {
        const q = usersSearch.toLowerCase();
        const matchSearch = !q
            || (u.displayName || '').toLowerCase().includes(q)
            || (u.mail || '').toLowerCase().includes(q)
            || (u.userPrincipalName || '').toLowerCase().includes(q);
        const matchStatus = !usersStatusFilter
            || (usersStatusFilter === 'active'   && u.accountEnabled !== false)
            || (usersStatusFilter === 'disabled' && u.accountEnabled === false);
        return matchSearch && matchStatus;
    });

    const expiredCount = licenses.filter(l => l.expiry_date && l.expiry_date < today).length;
    const soonCount    = licenses.filter(l => l.expiry_date && l.expiry_date >= today && l.expiry_date <= in30).length;

    if (loading) return <div className="main-content"><LoadingSpinner /></div>;

    return (
        <div className="main-content">
            <div className="container">

                {/* ── Header ─────────────────────────────────── */}
                <div className="page-header">
                    <div>
                        <h1>Software-Lizenzen</h1>
                        <p className="page-subtitle">
                            {licenses.length} Lizenz{licenses.length !== 1 ? 'en' : ''} verwaltet
                            {expiredCount > 0 && <span style={{ color: '#ef4444', marginLeft: '10px' }}>· {expiredCount} abgelaufen</span>}
                            {soonCount > 0 && <span style={{ color: '#f59e0b', marginLeft: '10px' }}>· {soonCount} läuft bald ab</span>}
                        </p>
                    </div>
                    {canEdit && (
                        <div style={{ display: 'flex', gap: '10px' }}>
                            <button className="btn btn-secondary" onClick={handleEntraImport} disabled={entraLoading}>
                                {entraLoading ? '⏳ Importiere...' : '☁️ Aus Entra importieren'}
                            </button>
                            <button className="btn btn-primary" onClick={openCreate}>+ Neue Lizenz</button>
                        </div>
                    )}
                </div>

                {/* ── Status-Karten ───────────────────────────── */}
                {(expiredCount > 0 || soonCount > 0) && (
                    <div style={{ display: 'flex', gap: '12px', marginBottom: '20px', flexWrap: 'wrap' }}>
                        {expiredCount > 0 && (
                            <div className="stat-card stat-card-danger" style={{ cursor: 'pointer', flex: 'none', padding: '12px 20px' }}
                                onClick={() => setFilterExpiry(filterExpiry === 'expired' ? '' : 'expired')}>
                                <div className="stat-icon" style={{ fontSize: '18px' }}>🔴</div>
                                <div className="stat-content">
                                    <div className="stat-value" style={{ fontSize: '22px' }}>{expiredCount}</div>
                                    <div className="stat-label">Abgelaufen</div>
                                </div>
                            </div>
                        )}
                        {soonCount > 0 && (
                            <div className="stat-card stat-card-warning" style={{ cursor: 'pointer', flex: 'none', padding: '12px 20px' }}
                                onClick={() => setFilterExpiry(filterExpiry === 'soon' ? '' : 'soon')}>
                                <div className="stat-icon" style={{ fontSize: '18px' }}>⚠️</div>
                                <div className="stat-content">
                                    <div className="stat-value" style={{ fontSize: '22px' }}>{soonCount}</div>
                                    <div className="stat-label">Läuft in 30 Tagen ab</div>
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* ── Filter ──────────────────────────────────── */}
                <div style={{ display: 'flex', gap: '10px', marginBottom: '20px', flexWrap: 'wrap', alignItems: 'center' }}>
                    <input type="text" className="form-control" placeholder="Suche nach Name oder Hersteller..."
                        value={search} onChange={(e) => setSearch(e.target.value)} style={{ maxWidth: '300px' }} />
                    <select className="form-control" value={filterType} onChange={(e) => setFilterType(e.target.value)} style={{ maxWidth: '170px' }}>
                        <option value="">Alle Typen</option>
                        {LICENSE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                    </select>
                    <select className="form-control" value={filterExpiry} onChange={(e) => setFilterExpiry(e.target.value)} style={{ maxWidth: '170px' }}>
                        <option value="">Alle Status</option>
                        <option value="expired">Abgelaufen</option>
                        <option value="soon">Läuft bald ab</option>
                        <option value="ok">Aktiv</option>
                    </select>
                    {(search || filterType || filterExpiry) && (
                        <button className="btn btn-secondary" onClick={() => { setSearch(''); setFilterType(''); setFilterExpiry(''); }}>
                            Zurücksetzen
                        </button>
                    )}
                    <span style={{ marginLeft: 'auto', color: 'var(--text-muted)', fontSize: '13px' }}>
                        {filtered.length} Ergebnis{filtered.length !== 1 ? 'se' : ''}
                    </span>
                </div>

                {/* ── Tabelle ─────────────────────────────────── */}
                <div className="card" style={{ overflowX: 'auto' }}>
                    <table className="table" style={{ tableLayout: 'fixed', minWidth: '1020px' }}>
                        <colgroup>
                            <col style={{ width: '24%' }} />
                            <col style={{ width: '12%' }} />
                            <col style={{ width: '11%' }} />
                            <col style={{ width: '11%' }} />
                            <col style={{ width: '9%' }} />
                            <col style={{ width: '10%' }} />
                            <col style={{ width: '8%' }} />
                            <col style={{ width: '15%' }} />
                        </colgroup>
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Hersteller</th>
                                <th>Typ</th>
                                <th>Seats / Nutzung</th>
                                <th>Kaufdatum</th>
                                <th>Ablaufdatum</th>
                                <th>Kosten (€)</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filtered.length === 0 ? (
                                <tr><td colSpan="8" style={{ textAlign: 'center', padding: '48px', color: 'var(--text-muted)' }}>
                                    Keine Lizenzen gefunden
                                </td></tr>
                            ) : filtered.map((license) => {
                                const status = getExpiryStatus(license.expiry_date);
                                const rowStyle = status === 'expired'
                                    ? { backgroundColor: 'rgba(239,68,68,0.06)', borderLeft: '3px solid #ef4444' }
                                    : status === 'soon'
                                    ? { backgroundColor: 'rgba(245,158,11,0.06)', borderLeft: '3px solid #f59e0b' }
                                    : {};
                                return (
                                    <tr key={license.id} style={rowStyle}>
                                        <td style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={license.name}>
                                            <span style={{ fontWeight: 600 }}>{license.name}</span>
                                        </td>
                                        <td style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                            <span title={license.vendor || ''} style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                                                <span>{VENDOR_ICON(license.vendor)}</span>
                                                <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>{license.vendor || '—'}</span>
                                            </span>
                                        </td>
                                        <td><TypeBadge type={license.license_type} /></td>
                                        <td><SeatsDisplay seats={license.seats} notes={license.notes} /></td>
                                        <td style={{ color: 'var(--text-muted)', fontSize: '13px' }}>
                                            {license.purchase_date ? new Date(license.purchase_date).toLocaleDateString('de-DE') : '—'}
                                        </td>
                                        <td>
                                            {license.expiry_date ? (
                                                <span style={{
                                                    display: 'flex', alignItems: 'center', gap: '5px', fontSize: '13px',
                                                    color: status === 'expired' ? '#ef4444' : status === 'soon' ? '#f59e0b' : 'var(--text-muted)',
                                                    fontWeight: status ? 600 : 400,
                                                }}>
                                                    {status === 'expired' && '🔴'}
                                                    {status === 'soon' && '⚠️'}
                                                    {new Date(license.expiry_date).toLocaleDateString('de-DE')}
                                                </span>
                                            ) : <span style={{ color: 'var(--text-muted)' }}>—</span>}
                                        </td>
                                        <td style={{ fontSize: '13px' }}>
                                            {license.cost !== null && license.cost !== undefined
                                                ? <span style={{ fontWeight: 600 }}>{parseFloat(license.cost).toLocaleString('de-DE', { minimumFractionDigits: 2 })} €</span>
                                                : <span style={{ color: 'var(--text-muted)' }}>—</span>}
                                        </td>
                                        <td>
                                            <div style={{ display: 'flex', gap: '5px', flexWrap: 'wrap' }}>
                                                {license.sku_id && (
                                                    <button
                                                        className="btn btn-sm btn-secondary"
                                                        onClick={() => openUsers(license)}
                                                        title="Zugewiesene Benutzer anzeigen"
                                                        style={{ padding: '4px 8px', minWidth: 0 }}
                                                    >👥</button>
                                                )}
                                                {canEdit && (<>
                                                    <button
                                                        className="btn btn-sm btn-secondary"
                                                        onClick={() => openEdit(license)}
                                                        title="Bearbeiten"
                                                        style={{ padding: '4px 8px', minWidth: 0 }}
                                                    >✏️</button>
                                                    <button
                                                        className="btn btn-sm btn-danger"
                                                        onClick={() => { setDeletingLicense(license); setShowDeleteModal(true); }}
                                                        title="Löschen"
                                                        style={{ padding: '4px 8px', minWidth: 0 }}
                                                    >🗑️</button>
                                                </>)}
                                            </div>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* ════════════ Create / Edit Modal ════════════ */}
            {showModal && (
                <div className="modal-overlay" onClick={() => setShowModal(false)}>
                    <div className="modal" style={{ maxWidth: '640px', width: '95%' }} onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <div>
                                <h2 style={{ margin: 0 }}>{editingLicense ? 'Lizenz bearbeiten' : 'Neue Lizenz'}</h2>
                                <p style={{ margin: '2px 0 0', fontSize: '13px', color: 'var(--text-muted)' }}>
                                    {editingLicense ? editingLicense.name : 'Neue Software-Lizenz anlegen'}
                                </p>
                            </div>
                            <button className="modal-close" onClick={() => setShowModal(false)}>×</button>
                        </div>
                        <form onSubmit={handleSave}>
                            <div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>

                                <Section title="Produkt">
                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                                        <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                            <label className="form-label">Name *</label>
                                            <input type="text" className="form-control" value={formData.name} onChange={set('name')}
                                                placeholder="z.B. Microsoft 365 Business Premium" required autoFocus />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Hersteller</label>
                                            <input type="text" className="form-control" value={formData.vendor} onChange={set('vendor')} placeholder="z.B. Microsoft" />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Lizenztyp</label>
                                            <select className="form-control" value={formData.license_type} onChange={set('license_type')}>
                                                {LICENSE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                                            </select>
                                        </div>
                                    </div>
                                </Section>

                                <Section title="Umfang & Kosten">
                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                                        <div className="form-group">
                                            <label className="form-label">Anzahl Seats</label>
                                            <input type="number" className="form-control" value={formData.seats} onChange={set('seats')}
                                                placeholder="Leer = unbegrenzt" min="1" />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Kosten (€)</label>
                                            <input type="number" className="form-control" value={formData.cost} onChange={set('cost')}
                                                placeholder="0.00" min="0" step="0.01" />
                                        </div>
                                    </div>
                                </Section>

                                <Section title="Laufzeit">
                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                                        <div className="form-group">
                                            <label className="form-label">Kaufdatum</label>
                                            <input type="date" className="form-control" value={formData.purchase_date} onChange={set('purchase_date')} />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Ablaufdatum</label>
                                            <input type="date" className="form-control" value={formData.expiry_date} onChange={set('expiry_date')}
                                                style={formData.expiry_date && formData.expiry_date < today
                                                    ? { borderColor: '#ef4444', color: '#ef4444' } : {}} />
                                        </div>
                                    </div>
                                </Section>

                                <Section title="Lizenzschlüssel">
                                    <div className="form-group">
                                        <div style={{ display: 'flex', gap: '8px' }}>
                                            <input
                                                type={showKey ? 'text' : 'password'}
                                                className="form-control"
                                                value={formData.product_key}
                                                onChange={set('product_key')}
                                                placeholder="XXXXX-XXXXX-XXXXX-XXXXX (optional)"
                                                style={{ fontFamily: 'monospace' }}
                                            />
                                            <button type="button" className="btn btn-secondary"
                                                onClick={() => setShowKey(!showKey)} style={{ whiteSpace: 'nowrap', minWidth: '100px' }}>
                                                {showKey ? '🙈 Verbergen' : '👁 Anzeigen'}
                                            </button>
                                        </div>
                                    </div>
                                </Section>

                                <Section title="Notizen">
                                    <div className="form-group">
                                        <textarea className="form-control" rows={3} value={formData.notes} onChange={set('notes')}
                                            placeholder="Weitere Informationen zur Lizenz..." style={{ resize: 'vertical' }} />
                                    </div>
                                </Section>
                            </div>
                            <div className="modal-footer">
                                <button type="button" className="btn btn-secondary" onClick={() => setShowModal(false)}>Abbrechen</button>
                                <button type="submit" className="btn btn-primary" disabled={saving}>
                                    {saving ? 'Speichern...' : (editingLicense ? 'Änderungen speichern' : 'Lizenz anlegen')}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* ════════════ Users Modal ════════════ */}
            {showUsersModal && usersLicense && (
                <div className="modal-overlay" onClick={() => setShowUsersModal(false)}
                    style={{ backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', background: 'rgba(0,0,0,0.65)' }}>
                    <div className="modal" style={{
                        maxWidth: '620px', width: '95%', overflow: 'hidden',
                        background: 'linear-gradient(160deg, var(--bg-card, #1e2433) 0%, var(--bg-secondary, #161b27) 100%)',
                        border: '1px solid rgba(255,255,255,0.08)',
                        boxShadow: '0 24px 64px rgba(0,0,0,0.5), 0 0 0 1px rgba(14,165,233,0.08)',
                    }} onClick={(e) => e.stopPropagation()}>

                        {/* Header with gradient accent */}
                        <div style={{
                            background: 'linear-gradient(135deg, rgba(14,165,233,0.12) 0%, rgba(99,102,241,0.08) 100%)',
                            borderBottom: '1px solid var(--border-color)',
                            padding: '20px 24px',
                            display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '12px',
                        }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '14px', minWidth: 0 }}>
                                <div style={{
                                    width: '44px', height: '44px', borderRadius: '12px', flexShrink: 0,
                                    background: 'rgba(14,165,233,0.15)', border: '1px solid rgba(14,165,233,0.25)',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '22px',
                                }}>👥</div>
                                <div style={{ minWidth: 0 }}>
                                    <h2 style={{ margin: 0, fontSize: '17px' }}>Zugewiesene Benutzer</h2>
                                    <p style={{ margin: '3px 0 0', fontSize: '13px', color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                        {VENDOR_ICON(usersLicense.vendor)}&nbsp;{usersLicense.name}
                                    </p>
                                </div>
                            </div>
                            <button className="modal-close" onClick={() => setShowUsersModal(false)} style={{ flexShrink: 0 }}>×</button>
                        </div>

                        {/* Stats bar */}
                        {!usersLoading && usersData.length > 0 && (
                            <div style={{ display: 'flex', borderBottom: '1px solid var(--border-color)' }}>
                                {[
                                    { key: '',         label: 'Gesamt',      value: usersData.length,                                           color: '#0ea5e9' },
                                    { key: 'active',   label: 'Aktiv',       value: usersData.filter(u => u.accountEnabled !== false).length,    color: '#10b981' },
                                    { key: 'disabled', label: 'Deaktiviert', value: usersData.filter(u => u.accountEnabled === false).length,     color: '#ef4444' },
                                ].map((s, i) => {
                                    const isActive = usersStatusFilter === s.key;
                                    return (
                                        <div key={i} onClick={() => setUsersStatusFilter(isActive ? '' : s.key)}
                                            style={{
                                                flex: 1, padding: '12px 16px', textAlign: 'center',
                                                cursor: 'pointer', userSelect: 'none',
                                                borderRight: i < 2 ? '1px solid var(--border-color)' : 'none',
                                                background: isActive ? `${s.color}18` : 'transparent',
                                                borderBottom: isActive ? `2px solid ${s.color}` : '2px solid transparent',
                                                transition: 'background 0.15s, border-color 0.15s',
                                            }}
                                        >
                                            <div style={{ fontSize: '20px', fontWeight: 700, color: s.color }}>{s.value}</div>
                                            <div style={{
                                                fontSize: '10.5px', textTransform: 'uppercase', letterSpacing: '0.06em',
                                                color: isActive ? s.color : 'var(--text-muted)',
                                                fontWeight: isActive ? 700 : 400,
                                                marginTop: '2px',
                                            }}>{s.label}</div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}

                        <div className="modal-body" style={{ padding: '16px 20px' }}>
                            {usersLoading ? (
                                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '48px', gap: '14px' }}>
                                    <LoadingSpinner />
                                    <span style={{ color: 'var(--text-muted)', fontSize: '13px' }}>Benutzer werden aus Entra ID geladen…</span>
                                </div>
                            ) : usersData.length === 0 ? (
                                <div style={{ textAlign: 'center', padding: '48px', color: 'var(--text-muted)' }}>
                                    <div style={{ fontSize: '40px', marginBottom: '12px', opacity: 0.5 }}>👤</div>
                                    <div style={{ fontWeight: 600, marginBottom: '4px' }}>Keine Benutzer gefunden</div>
                                    <div style={{ fontSize: '13px' }}>Dieser Lizenz ist kein Benutzer zugewiesen</div>
                                </div>
                            ) : (
                                <>
                                    {/* Search */}
                                    <div style={{ position: 'relative', marginBottom: '14px' }}>
                                        <svg style={{
                                            position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)',
                                            color: 'var(--text-muted)', pointerEvents: 'none', flexShrink: 0,
                                        }} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                                        </svg>
                                        <input
                                            type="text"
                                            className="form-control"
                                            placeholder="Name oder E-Mail suchen…"
                                            value={usersSearch}
                                            onChange={(e) => setUsersSearch(e.target.value)}
                                            style={{
                                                paddingLeft: '38px',
                                                background: 'rgba(255,255,255,0.04)',
                                                border: '1px solid rgba(255,255,255,0.1)',
                                                borderRadius: '10px',
                                                fontSize: '13.5px',
                                                transition: 'border-color 0.2s, box-shadow 0.2s',
                                            }}
                                            onFocus={e => { e.target.style.borderColor = 'rgba(14,165,233,0.5)'; e.target.style.boxShadow = '0 0 0 3px rgba(14,165,233,0.1)'; }}
                                            onBlur={e => { e.target.style.borderColor = 'rgba(255,255,255,0.1)'; e.target.style.boxShadow = 'none'; }}
                                            autoFocus
                                        />
                                        {usersSearch && (
                                            <button onClick={() => setUsersSearch('')} style={{
                                                position: 'absolute', right: '10px', top: '50%', transform: 'translateY(-50%)',
                                                background: 'none', border: 'none', cursor: 'pointer',
                                                color: 'var(--text-muted)', fontSize: '16px', lineHeight: 1, padding: '2px',
                                            }}>×</button>
                                        )}
                                    </div>

                                    {/* User list */}
                                    <div style={{ maxHeight: '360px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '5px',
                                        paddingRight: '2px',
                                    }}>
                                        {filteredUsers.length === 0 ? (
                                            <div style={{ textAlign: 'center', padding: '28px', color: 'var(--text-muted)', fontSize: '13px' }}>
                                                Kein Treffer für „{usersSearch}"
                                            </div>
                                        ) : filteredUsers.map((user) => {
                                            const initials = (user.displayName || '?').split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();
                                            const disabled = user.accountEnabled === false;
                                            // Deterministic avatar color from name
                                            const colors = ['#0ea5e9','#8b5cf6','#10b981','#f59e0b','#ef4444','#ec4899','#14b8a6'];
                                            const colorIdx = (user.displayName || '').charCodeAt(0) % colors.length;
                                            const avatarColor = colors[colorIdx];
                                            return (
                                                <div key={user.id} style={{
                                                    display: 'flex', alignItems: 'center', gap: '12px',
                                                    padding: '10px 12px', borderRadius: '10px',
                                                    background: 'var(--bg-secondary)',
                                                    border: '1px solid var(--border-color)',
                                                    transition: 'border-color 0.15s',
                                                    opacity: disabled ? 0.5 : 1,
                                                }}>
                                                    {/* Avatar */}
                                                    <div style={{
                                                        width: '38px', height: '38px', borderRadius: '10px', flexShrink: 0,
                                                        background: `${avatarColor}22`,
                                                        border: `1px solid ${avatarColor}44`,
                                                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                                                        fontSize: '13px', fontWeight: 700, color: avatarColor,
                                                        letterSpacing: '-0.5px',
                                                    }}>
                                                        {initials}
                                                    </div>
                                                    {/* Info */}
                                                    <div style={{ overflow: 'hidden', flex: 1, minWidth: 0 }}>
                                                        <div style={{
                                                            fontWeight: 600, fontSize: '13.5px',
                                                            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                                                        }}>
                                                            {user.displayName || user.userPrincipalName}
                                                        </div>
                                                        <div style={{
                                                            fontSize: '12px', color: 'var(--text-muted)',
                                                            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                                                        }}>
                                                            {user.mail || user.userPrincipalName}
                                                        </div>
                                                    </div>
                                                    {/* Status */}
                                                    {disabled ? (
                                                        <span style={{
                                                            fontSize: '11px', padding: '3px 9px', borderRadius: '20px', flexShrink: 0,
                                                            background: 'rgba(239,68,68,0.1)', color: '#ef4444',
                                                            border: '1px solid rgba(239,68,68,0.2)', fontWeight: 600,
                                                        }}>Deaktiviert</span>
                                                    ) : (
                                                        <span style={{
                                                            fontSize: '11px', padding: '3px 9px', borderRadius: '20px', flexShrink: 0,
                                                            background: 'rgba(16,185,129,0.1)', color: '#10b981',
                                                            border: '1px solid rgba(16,185,129,0.2)', fontWeight: 600,
                                                        }}>Aktiv</span>
                                                    )}
                                                </div>
                                            );
                                        })}
                                    </div>
                                </>
                            )}
                        </div>

                        <div className="modal-footer">
                            {!usersLoading && usersData.length > 0 && (
                                <span style={{ fontSize: '12px', color: 'var(--text-muted)', marginRight: 'auto' }}>
                                    {filteredUsers.length} von {usersData.length} Benutzer{usersData.length !== 1 ? 'n' : ''}
                                    {(usersSearch || usersStatusFilter) && (
                                        <button onClick={() => { setUsersSearch(''); setUsersStatusFilter(''); }}
                                            style={{ marginLeft: '10px', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: '12px', textDecoration: 'underline', padding: 0 }}>
                                            Filter zurücksetzen
                                        </button>
                                    )}
                                </span>
                            )}
                            <button className="btn btn-secondary" onClick={() => setShowUsersModal(false)}>Schließen</button>
                        </div>
                    </div>
                </div>
            )}

            {/* ════════════ Delete Modal ════════════ */}
            {showDeleteModal && deletingLicense && (
                <div className="modal-overlay" onClick={() => setShowDeleteModal(false)}>
                    <div className="modal" style={{ maxWidth: '420px' }} onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2>Lizenz löschen</h2>
                            <button className="modal-close" onClick={() => setShowDeleteModal(false)}>×</button>
                        </div>
                        <div className="modal-body">
                            <p>Soll <strong>{deletingLicense.name}</strong> wirklich gelöscht werden?</p>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setShowDeleteModal(false)}>Abbrechen</button>
                            <button className="btn btn-danger" onClick={handleDelete}>Löschen</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default LicensesPage;
