{% extends "base.html" %}
{% block title %}Nutzerverwaltung - Admin{% endblock %}

{% block content %}
<div class="mb-8">
    <h1 class="text-3xl font-bold text-white mb-2">Nutzerverwaltung</h1>
    <p class="text-gray-400">Alle Benutzer und Firmen verwalten</p>
</div>

{% if error %}
<div class="bg-red-900/50 border border-red-500 text-red-200 px-4 py-3 rounded-lg mb-6">
    <strong>Error:</strong> {{ error }}
</div>
{% endif %}

<!-- Summary Cards -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
    <div class="card-bg rounded-xl border p-6">
        <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-brand-highlight/20 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
            </div>
            <div>
                <p class="text-gray-400 text-sm">Gesamt Nutzer</p>
                <p class="text-2xl font-bold text-white">{{ total_users }}</p>
            </div>
        </div>
    </div>
    <div class="card-bg rounded-xl border p-6">
        <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-blue-600/20 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
            </div>
            <div>
                <p class="text-gray-400 text-sm">Firmen</p>
                <p class="text-2xl font-bold text-white">{{ total_companies }}</p>
            </div>
        </div>
    </div>
    <div class="card-bg rounded-xl border p-6">
        <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-green-600/20 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
            </div>
            <div>
                <p class="text-gray-400 text-sm">Ghostwriter</p>
                <p class="text-2xl font-bold text-white">{{ total_ghostwriters }}</p>
            </div>
        </div>
    </div>
    <div class="card-bg rounded-xl border p-6">
        <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-purple-600/20 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"/></svg>
            </div>
            <div>
                <p class="text-gray-400 text-sm">Mitarbeiter</p>
                <p class="text-2xl font-bold text-white">{{ total_employees }}</p>
            </div>
        </div>
    </div>
</div>

<!-- Search -->
<div class="mb-6">
    <input type="text" id="searchInput" placeholder="Suche nach Name oder E-Mail..."
           class="w-full max-w-md input-bg border rounded-lg px-4 py-2 text-white placeholder-gray-400"
           oninput="filterUsers()">
</div>

<!-- Tabs -->
<div class="flex gap-2 mb-6">
    <button onclick="showTab('companies')" id="tab-companies"
            class="px-5 py-2 rounded-lg font-medium transition-colors btn-primary">
        Firmen ({{ total_companies }})
    </button>
    <button onclick="showTab('ghostwriters')" id="tab-ghostwriters"
            class="px-5 py-2 rounded-lg font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg">
        Ghostwriter ({{ total_ghostwriters }})
    </button>
</div>

<!-- Companies Tab -->
<div id="content-companies" class="space-y-4">
    {% for cd in company_data %}
    <div class="card-bg rounded-xl border overflow-hidden user-card" data-search="{{ cd.company.name|lower }} {{ cd.owner.email|lower if cd.owner else '' }} {{ cd.owner.display_name|lower if cd.owner and cd.owner.display_name else '' }}">
        <!-- Company Header (clickable to expand) -->
        <div class="p-5 cursor-pointer hover:bg-brand-bg-light/50 transition-colors" onclick="toggleCompany('company-{{ cd.company.id }}')">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-4">
                    <div class="w-10 h-10 bg-blue-600/30 rounded-lg flex items-center justify-center">
                        <svg class="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-white">{{ cd.company.name }}</h3>
                        <p class="text-sm text-gray-400">
                            Owner: {{ cd.owner.display_name or cd.owner.email if cd.owner else 'Unbekannt' }}
                            | {{ cd.employee_count }} Mitarbeiter
                        </p>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    {% if cd.owner %}
                    <a href="/admin/impersonate/{{ cd.owner.id }}" class="px-3 py-1.5 text-xs bg-brand-highlight/20 text-brand-highlight rounded-lg hover:bg-brand-highlight/30 transition-colors"
                       title="Als Owner einloggen" onclick="event.stopPropagation()">
                        Impersonate
                    </a>
                    {% endif %}
                    <svg class="w-5 h-5 text-gray-400 transition-transform" id="chevron-company-{{ cd.company.id }}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                </div>
            </div>
        </div>

        <!-- Expandable Details -->
        <div id="company-{{ cd.company.id }}" class="hidden border-t border-gray-600">
            <!-- Owner -->
            {% if cd.owner %}
            <div class="px-5 py-3 bg-brand-bg/30 border-b border-gray-600/50">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <span class="text-xs font-medium px-2 py-0.5 bg-blue-600/30 text-blue-300 rounded">OWNER</span>
                        <span class="text-sm text-white">{{ cd.owner.display_name or cd.owner.email }}</span>
                        <span class="text-xs text-gray-400">{{ cd.owner.email }}</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-400">{{ cd.owner.onboarding_status.value if cd.owner.onboarding_status and cd.owner.onboarding_status.value else cd.owner.onboarding_status }}</span>
                        <button onclick="deleteUser('{{ cd.owner.id }}', '{{ cd.owner.display_name or cd.owner.email }}')"
                                class="text-red-400 hover:text-red-300 p-1" title="Nutzer löschen">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        </button>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- Employees -->
            {% for emp in cd.employees %}
            <div class="px-5 py-3 border-b border-gray-600/30 hover:bg-brand-bg/20">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <span class="text-xs font-medium px-2 py-0.5 bg-purple-600/30 text-purple-300 rounded">EMPLOYEE</span>
                        <span class="text-sm text-white">{{ emp.display_name or emp.email }}</span>
                        <span class="text-xs text-gray-400">{{ emp.email }}</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-400">{{ emp.onboarding_status.value if emp.onboarding_status and emp.onboarding_status.value else emp.onboarding_status }}</span>
                        <a href="/admin/impersonate/{{ emp.id }}" class="text-brand-highlight hover:text-brand-highlight-dark p-1" title="Als Mitarbeiter einloggen">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/></svg>
                        </a>
                        <button onclick="deleteUser('{{ emp.id }}', '{{ emp.display_name or emp.email }}')"
                                class="text-red-400 hover:text-red-300 p-1" title="Nutzer löschen">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        </button>
                    </div>
                </div>
            </div>
            {% endfor %}

            {% if cd.employees|length == 0 %}
            <div class="px-5 py-3 text-sm text-gray-500 italic">Keine Mitarbeiter</div>
            {% endif %}
        </div>
    </div>
    {% endfor %}

    {% if company_data|length == 0 %}
    <div class="card-bg rounded-xl border p-8 text-center text-gray-400">
        Keine Firmen vorhanden
    </div>
    {% endif %}
</div>

<!-- Ghostwriters Tab -->
<div id="content-ghostwriters" class="hidden space-y-3">
    {% for gw in ghostwriters %}
    {% set profile = gw %}
    <div class="card-bg rounded-xl border p-5 user-card" data-search="{{ gw.display_name|lower if gw.display_name else '' }} {{ gw.email|lower }}">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
                <div class="w-10 h-10 bg-green-600/30 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                </div>
                <div>
                    <h3 class="text-white font-medium">{{ gw.display_name or gw.email }}</h3>
                    <p class="text-sm text-gray-400">
                        {{ gw.email }}
                        | Status: {{ gw.onboarding_status.value if gw.onboarding_status and gw.onboarding_status.value else gw.onboarding_status }}
                    </p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <a href="/admin/impersonate/{{ gw.id }}" class="px-3 py-1.5 text-xs bg-brand-highlight/20 text-brand-highlight rounded-lg hover:bg-brand-highlight/30 transition-colors">
                    Impersonate
                </a>
                <button onclick="deleteUser('{{ gw.id }}', '{{ gw.display_name or gw.email }}')"
                        class="text-red-400 hover:text-red-300 p-1.5 rounded-lg hover:bg-red-400/10 transition-colors" title="Nutzer löschen">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                </button>
            </div>
        </div>
    </div>
    {% endfor %}

    {% if ghostwriters|length == 0 %}
    <div class="card-bg rounded-xl border p-8 text-center text-gray-400">
        Keine Ghostwriter vorhanden
    </div>
    {% endif %}
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50">
    <div class="card-bg rounded-xl border p-6 max-w-md w-full mx-4">
        <h3 class="text-lg font-semibold text-white mb-2">Nutzer löschen</h3>
        <p class="text-gray-300 mb-4">Bist du sicher, dass du <strong id="deleteUserName" class="text-red-400"></strong> und alle zugehörigen Daten löschen möchtest? Dies kann nicht rückgängig gemacht werden.</p>
        <div class="flex justify-end gap-3">
            <button onclick="closeDeleteModal()" class="px-4 py-2 rounded-lg bg-brand-bg-light text-gray-300 hover:bg-brand-bg transition-colors">Abbrechen</button>
            <button onclick="confirmDelete()" class="px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-700 transition-colors">Löschen</button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentTab = 'companies';
let deleteUserId = null;

function showTab(tab) {
    document.getElementById('content-companies').classList.toggle('hidden', tab !== 'companies');
    document.getElementById('content-ghostwriters').classList.toggle('hidden', tab !== 'ghostwriters');

    document.getElementById('tab-companies').className = tab === 'companies'
        ? 'px-5 py-2 rounded-lg font-medium transition-colors btn-primary'
        : 'px-5 py-2 rounded-lg font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg';
    document.getElementById('tab-ghostwriters').className = tab === 'ghostwriters'
        ? 'px-5 py-2 rounded-lg font-medium transition-colors btn-primary'
        : 'px-5 py-2 rounded-lg font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg';

    currentTab = tab;
    filterUsers();
}

function toggleCompany(id) {
    const el = document.getElementById(id);
    const chevron = document.getElementById('chevron-' + id);
    el.classList.toggle('hidden');
    chevron.style.transform = el.classList.contains('hidden') ? '' : 'rotate(180deg)';
}

function filterUsers() {
    const query = document.getElementById('searchInput').value.toLowerCase().trim();
    const container = document.getElementById('content-' + currentTab);
    const cards = container.querySelectorAll('.user-card');

    cards.forEach(card => {
        const search = card.getAttribute('data-search') || '';
        card.style.display = !query || search.includes(query) ? '' : 'none';
    });
}

function deleteUser(userId, name) {
    deleteUserId = userId;
    document.getElementById('deleteUserName').textContent = name;
    document.getElementById('deleteModal').classList.remove('hidden');
}

function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
    deleteUserId = null;
}

async function confirmDelete() {
    if (!deleteUserId) return;
    try {
        const resp = await fetch(`/admin/api/users/${deleteUserId}`, { method: 'DELETE' });
        if (resp.ok) {
            window.location.reload();
        } else {
            const data = await resp.json();
            alert('Fehler: ' + (data.detail || 'Unbekannter Fehler'));
        }
    } catch (e) {
        alert('Fehler: ' + e.message);
    }
    closeDeleteModal();
}
</script>
{% endblock %}
