{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}{% trans "Hospital Users" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    .page-header-gradient {
        background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-radius: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
    }

    .section-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .section-card:hover {
        border-color: #005696;
        box-shadow: 0 10px 25px -5px rgba(0, 86, 150, 0.15);
    }

    .section-header {
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #e2e8f0;
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .section-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .stat-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        padding: 1.5rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: #005696;
    }

    .filter-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        overflow: hidden;
        margin-bottom: 1.5rem;
        transition: all 0.3s ease;
    }
    .filter-card:hover {
        border-color: #005696;
    }

    .filter-header {
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #e2e8f0;
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .table-row-hover {
        transition: all 0.2s ease;
        border-left: 3px solid transparent;
    }
    .table-row-hover:hover {
        background: #f8fafc;
        border-left-color: #007bbd;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.375rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
</style>
{% endblock %}

{% block content %}
<div class="p-6">
    <!-- Page Header -->
    <div class="page-header-gradient">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold mb-1">{% trans "Hospital Users" %}</h1>
                <p class="text-blue-100 text-sm">{% trans "Manage hospital user accounts and reset passwords" %}</p>
            </div>
            <a href="{% url 'config:dashboard' %}" class="inline-flex items-center px-4 py-2.5 bg-white text-navy font-medium rounded-xl hover:bg-blue-50 transition">
                <i data-lucide="arrow-left" class="w-4 h-4 me-2"></i>{% trans "Back to Config" %}
            </a>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-navy/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="users" class="w-6 h-6 text-navy"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Total Users" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ total_users }}</h2>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-green-500/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="user-check" class="w-6 h-6 text-green-600"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Active" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ active_count }}</h2>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-red-500/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="user-x" class="w-6 h-6 text-red-600"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Inactive" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ inactive_count }}</h2>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-card">
        <div class="filter-header">
            <div class="section-icon bg-navy/10">
                <i data-lucide="filter" class="w-5 h-5 text-navy"></i>
            </div>
            <h5 class="text-base font-semibold text-gray-800">{% trans "Filters" %}</h5>
        </div>
        <div class="p-5">
            <form method="get" class="flex flex-wrap gap-4 items-end">
                {% if user.is_px_admin %}
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-slate uppercase">{% trans "Hospital" %}</label>
                    <select name="hospital" class="px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-navy">
                        <option value="">{% trans "All" %}</option>
                        {% for hospital in hospitals %}
                        <option value="{{ hospital.id }}" {% if request.GET.hospital == hospital.id|stringformat:"s" %}selected{% endif %}>{{ hospital.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                {% endif %}
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-slate uppercase">{% trans "Role" %}</label>
                    <select name="role" class="px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-navy">
                        <option value="">{% trans "All" %}</option>
                        {% for role in roles %}
                        <option value="{{ role.name }}" {% if request.GET.role == role.name %}selected{% endif %}>{{ role.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-slate uppercase">{% trans "Status" %}</label>
                    <select name="is_active" class="px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-navy">
                        <option value="">{% trans "All" %}</option>
                        <option value="true" {% if request.GET.is_active == 'true' %}selected{% endif %}>{% trans "Active" %}</option>
                        <option value="false" {% if request.GET.is_active == 'false' %}selected{% endif %}>{% trans "Inactive" %}</option>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-slate uppercase">{% trans "Search" %}</label>
                    <input type="text" name="search" class="px-3 py-1.5 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-navy w-40" placeholder="{% trans 'Name, email, ID...' %}" value="{{ request.GET.search|default:'' }}">
                </div>
                <div class="flex items-center gap-2">
                    <button type="submit" class="px-4 py-1.5 bg-navy text-white rounded-lg text-xs font-bold hover:bg-blue transition">{% trans "Apply" %}</button>
                    <a href="{% url 'config:hospital_users_list' %}" class="px-4 py-1.5 border border-slate-200 rounded-lg text-xs font-semibold text-slate hover:bg-light transition">{% trans "Clear" %}</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Users List Section -->
    <div class="section-card">
        <div class="section-header flex justify-between items-center">
            <div class="flex items-center gap-3">
                <div class="section-icon bg-navy/10">
                    <i data-lucide="users" class="w-5 h-5 text-navy"></i>
                </div>
                <h5 class="text-lg font-semibold text-gray-800">{% trans "User Accounts" %}</h5>
            </div>
            <div class="text-xs text-slate font-medium">
                {% trans "Showing" %} <span class="font-bold text-navy">{{ page_obj.start_index|default:0 }}-{{ page_obj.end_index|default:0 }}</span> {% trans "of" %} <span class="font-bold text-navy">{{ page_obj.paginator.count|default:0 }}</span>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-slate-50 border-b border-slate-200">
                    <tr class="text-xs font-bold text-slate uppercase tracking-wider">
                        <th class="px-5 py-3 text-left">{% trans "Name" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Email" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Hospital" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Department" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Role(s)" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Status" %}</th>
                        <th class="px-5 py-3 text-left">{% trans "Actions" %}</th>
                    </tr>
                </thead>
                <tbody class="text-sm divide-y divide-slate-100">
                    {% for u in users %}
                    <tr class="table-row-hover">
                        <td class="px-5 py-4">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-navy rounded-full flex items-center justify-center text-white font-bold text-xs">
                                    {{ u.first_name.0 }}{{ u.last_name.0 }}
                                </div>
                                <div>
                                    <div class="font-bold text-navy">{{ u.get_full_name }}</div>
                                    {% if u.employee_id %}
                                    <div class="text-xs text-slate">{{ u.employee_id }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </td>
                        <td class="px-5 py-4 text-slate-800">{{ u.email }}</td>
                        <td class="px-5 py-4">
                            {% if u.hospital %}
                            <span class="px-2 py-1 rounded-lg text-xs font-bold bg-blue-50 text-blue-700">{{ u.hospital.name }}</span>
                            {% else %}
                            <span class="text-slate text-xs">-</span>
                            {% endif %}
                        </td>
                        <td class="px-5 py-4">
                            {% if u.department %}
                            <span class="px-2 py-1 rounded-lg text-xs font-bold bg-slate-100 text-slate-600">{{ u.department.get_localized_name }}</span>
                            {% else %}
                            <span class="text-slate text-xs">-</span>
                            {% endif %}
                        </td>
                        <td class="px-5 py-4">
                            {% for role_name in u.get_role_names %}
                            <span class="inline-block px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-50 text-purple-700 mr-1 mb-1">{{ role_name }}</span>
                            {% empty %}
                            <span class="text-slate text-xs">-</span>
                            {% endfor %}
                        </td>
                        <td class="px-5 py-4">
                            {% if u.is_active %}
                            <span class="status-badge bg-green-100 text-green-600">{% trans "Active" %}</span>
                            {% else %}
                            <span class="status-badge bg-red-100 text-red-600">{% trans "Inactive" %}</span>
                            {% endif %}
                        </td>
                        <td class="px-5 py-4">
                            {% if user.is_px_admin %}
                            <button type="button" class="p-1.5 text-orange-600 hover:bg-orange-50 rounded-lg transition" onclick="openResetModal('{{ u.id }}', '{{ u.get_full_name }}', '{{ u.email }}')" title="{% trans 'Reset Password' %}">
                                <i data-lucide="key-round" class="w-4 h-4"></i>
                            </button>
                            <button type="button" class="p-1.5 hover:bg-slate-100 rounded-lg transition {% if u.is_active %}text-red-600 hover:bg-red-50{% else %}text-green-600 hover:bg-green-50{% endif %}"
                                    onclick="openToggleModal('{{ u.id }}', '{{ u.get_full_name }}', {{ u.is_active|lower }})"
                                    title="{% if u.is_active %}{% trans 'Deactivate User' %}{% else %}{% trans 'Activate User' %}{% endif %}">
                                <i data-lucide="{% if u.is_active %}user-x{% else %}user-check{% endif %}" class="w-4 h-4"></i>
                            </button>
                            {% else %}
                            <button type="button" class="p-1.5 text-orange-600 hover:bg-orange-50 rounded-lg transition" onclick="openResetModal('{{ u.id }}', '{{ u.get_full_name }}', '{{ u.email }}')" title="{% trans 'Reset Password' %}">
                                <i data-lucide="key-round" class="w-4 h-4"></i>
                            </button>
                            {% endif %}
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="7" class="px-5 py-12 text-center">
                            <div class="flex flex-col items-center justify-center">
                                <div class="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                                    <i data-lucide="users" class="w-8 h-8 text-slate-300"></i>
                                </div>
                                <p class="text-slate font-medium mb-2">{% trans "No users found" %}</p>
                                <p class="text-slate text-sm">{% trans "Try adjusting your filters" %}</p>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        {% if page_obj.has_other_pages %}
        <div class="bg-slate-50 px-6 py-4 flex items-center justify-between border-t border-slate-100">
            <div class="flex items-center gap-4">
                <span class="text-xs text-slate font-medium">
                    {% trans "Showing" %} <span class="font-bold text-navy">{{ page_obj.start_index }}-{{ page_obj.end_index }}</span> {% trans "of" %} <span class="font-bold text-navy">{{ page_obj.paginator.count }}</span> {% trans "entries" %}
                </span>
                <form method="get" class="flex items-center gap-2" id="pageSizeForm">
                    {% for key, value in request.GET.items %}
                        {% if key != 'page_size' and key != 'page' %}
                        <input type="hidden" name="{{ key }}" value="{{ value }}">
                        {% endif %}
                    {% endfor %}
                    <label class="text-xs text-slate">{% trans "Show" %}</label>
                    <select name="page_size" onchange="document.getElementById('pageSizeForm').submit()" class="px-2 py-1 bg-white border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-navy">
                        <option value="10" {% if page_obj.paginator.per_page == 10 %}selected{% endif %}>10</option>
                        <option value="25" {% if page_obj.paginator.per_page == 25 %}selected{% endif %}>25</option>
                        <option value="50" {% if page_obj.paginator.per_page == 50 %}selected{% endif %}>50</option>
                        <option value="100" {% if page_obj.paginator.per_page == 100 %}selected{% endif %}>100</option>
                    </select>
                </form>
            </div>
            <div class="flex gap-1">
                {% if page_obj.has_previous %}
                <a href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"
                   class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition">
                    <i data-lucide="chevron-left" class="w-4 h-4 text-slate"></i>
                </a>
                {% else %}
                <span class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-slate-100 text-slate-300 cursor-not-allowed">
                    <i data-lucide="chevron-left" class="w-4 h-4"></i>
                </span>
                {% endif %}

                {% for num in page_obj.paginator.page_range %}
                    {% if num == page_obj.number %}
                    <span class="w-8 h-8 flex items-center justify-center rounded-lg bg-navy text-white text-xs font-bold">{{ num }}</span>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <a href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"
                       class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-xs font-bold text-slate transition">
                        {{ num }}
                    </a>
                    {% elif num == 1 or num == page_obj.paginator.num_pages %}
                    <a href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"
                       class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-xs font-bold text-slate transition">
                        {{ num }}
                    </a>
                    {% elif num == page_obj.number|add:'-3' or num == page_obj.number|add:'3' %}
                    <span class="w-8 h-8 flex items-center justify-center text-xs text-slate">...</span>
                    {% endif %}
                {% endfor %}

                {% if page_obj.has_next %}
                <a href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"
                   class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition">
                    <i data-lucide="chevron-right" class="w-4 h-4 text-slate"></i>
                </a>
                {% else %}
                <span class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-slate-100 text-slate-300 cursor-not-allowed">
                    <i data-lucide="chevron-right" class="w-4 h-4"></i>
                </span>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Reset Password Confirmation Modal -->
<div class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50" id="resetPasswordModal">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 overflow-hidden">
        <div class="bg-orange-500 text-white px-6 py-4 flex justify-between items-center">
            <h5 class="font-bold text-lg flex items-center gap-2">
                <i data-lucide="key-round" class="w-5 h-5"></i>
                {% trans "Reset Password" %}
            </h5>
            <button type="button" class="text-white hover:bg-orange-600 rounded-full p-1 transition" onclick="closeModal('resetPasswordModal')">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="p-6">
            <p class="text-slate mb-2">{% trans "Reset password for" %} <strong class="text-navy" id="resetUserName"></strong>?</p>
            <p class="text-slate text-sm mb-1">{% trans "Email:" %} <span id="resetUserEmail" class="font-medium"></span></p>
            <p class="text-slate text-sm">{% trans "A secure password reset link will be sent to this user's email." %}</p>
        </div>
        <div class="px-6 py-4 bg-slate-50 flex justify-end gap-3">
            <button type="button" class="px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-white transition" onclick="closeModal('resetPasswordModal')">{% trans "Cancel" %}</button>
            <button type="button" id="confirmResetBtn" class="px-4 py-2 bg-orange-500 text-white rounded-xl font-semibold hover:bg-orange-600 transition" onclick="confirmResetPassword()">{% trans "Reset Password" %}</button>
        </div>
    </div>
</div>

<!-- Reset Password Success Modal -->
<div class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50" id="resetSuccessModal">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 overflow-hidden">
        <div class="bg-green-600 text-white px-6 py-4 flex justify-between items-center">
            <h5 class="font-bold text-lg flex items-center gap-2">
                <i data-lucide="check-circle" class="w-5 h-5"></i>
                {% trans "Password Reset Successfully" %}
            </h5>
            <button type="button" class="text-white hover:bg-green-700 rounded-full p-1 transition" onclick="closeModal('resetSuccessModal')">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="p-6">
            <p class="text-slate mb-3">{% trans "The password reset link has been sent to" %} <strong class="text-navy" id="successUserName"></strong>.</p>
            <div class="p-3 bg-blue-50 border-l-4 border-blue-400 rounded-r-lg">
                <p class="text-xs text-blue-800">
                    <strong>{% trans "Note:" %}</strong> {% trans "No password is shown or stored. The user must use the email link to set a new password." %}
                </p>
            </div>
        </div>
        <div class="px-6 py-4 bg-slate-50 flex justify-end">
            <button type="button" class="px-4 py-2 bg-navy text-white rounded-xl font-semibold hover:bg-blue transition" onclick="closeModal('resetSuccessModal')">{% trans "Done" %}</button>
        </div>
    </div>
</div>

<!-- Toggle User Active Status Modal -->
<div class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50" id="toggleUserModal">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 overflow-hidden">
        <div id="toggleModalHeader" class="text-white px-6 py-4 flex justify-between items-center">
            <h5 class="font-bold text-lg flex items-center gap-2">
                <i data-lucide="user-x" class="w-5 h-5"></i>
                <span id="toggleModalTitle">{% trans "Deactivate User" %}</span>
            </h5>
            <button type="button" class="text-white hover:bg-white/20 rounded-full p-1 transition" onclick="closeModal('toggleUserModal')">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="p-6">
            <p class="text-slate mb-3" id="toggleModalMessage"></p>
            <div class="bg-slate-50 rounded-xl border border-slate-200 p-4 mb-4">
                <p class="text-xs text-slate mb-2 uppercase font-bold">{% trans "Confirm Your Password" %}</p>
                <input type="password" id="toggleAdminPassword" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-navy" placeholder="{% trans 'Enter your password to confirm' %}">
                <p class="text-xs text-red-600 mt-1 hidden" id="togglePasswordError"></p>
            </div>
        </div>
        <div class="px-6 py-4 bg-slate-50 flex justify-end gap-3">
            <button type="button" class="px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-white transition" onclick="closeModal('toggleUserModal')">{% trans "Cancel" %}</button>
            <button type="button" id="confirmToggleBtn" class="px-4 py-2 rounded-xl font-semibold text-white transition" onclick="confirmToggleUser()">{% trans "Confirm" %}</button>
        </div>
    </div>
</div>

<!-- Toggle User Success Modal -->
<div class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50" id="toggleSuccessModal">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 overflow-hidden">
        <div class="bg-green-600 text-white px-6 py-4 flex justify-between items-center">
            <h5 class="font-bold text-lg flex items-center gap-2">
                <i data-lucide="check-circle" class="w-5 h-5"></i>
                <span id="toggleSuccessTitle">{% trans "User Status Updated" %}</span>
            </h5>
            <button type="button" class="text-white hover:bg-green-700 rounded-full p-1 transition" onclick="closeToggleSuccess()">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="p-6">
            <p class="text-slate" id="toggleSuccessMessage"></p>
        </div>
        <div class="px-6 py-4 bg-slate-50 flex justify-end">
            <button type="button" class="px-4 py-2 bg-navy text-white rounded-xl font-semibold hover:bg-blue transition" onclick="closeToggleSuccess()">{% trans "Done" %}</button>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
let currentUserId = null;

function closeModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
}

function showModal(modalId) {
    document.getElementById(modalId).classList.remove('hidden');
}

function openResetModal(userId, userName, userEmail) {
    currentUserId = userId;
    document.getElementById('resetUserName').textContent = userName;
    document.getElementById('resetUserEmail').textContent = userEmail;
    showModal('resetPasswordModal');
}

function confirmResetPassword() {
    const btn = document.getElementById('confirmResetBtn');
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin inline"></i> {% trans "Resetting..." %}';

    fetch(`/config/users/${currentUserId}/reset-password/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        }
    })
    .then(response => response.json())
    .then(data => {
        closeModal('resetPasswordModal');
        if (data.success) {
            document.getElementById('successUserName').textContent = data.user_name;
            showModal('resetSuccessModal');
            lucide.createIcons();
        } else {
            alert(data.error || 'An error occurred.');
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '{% trans "Reset Password" %}';
    });
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});

let toggleUserId = null;
let toggleUserCurrentActive = null;

function openToggleModal(userId, userName, isCurrentlyActive) {
    toggleUserId = userId;
    toggleUserCurrentActive = isCurrentlyActive;

    const header = document.getElementById('toggleModalHeader');
    const title = document.getElementById('toggleModalTitle');
    const message = document.getElementById('toggleModalMessage');
    const btn = document.getElementById('confirmToggleBtn');
    const passwordInput = document.getElementById('toggleAdminPassword');
    const passwordError = document.getElementById('togglePasswordError');

    passwordInput.value = '';
    passwordError.classList.add('hidden');

    if (isCurrentlyActive) {
        header.className = 'bg-red-600 text-white px-6 py-4 flex justify-between items-center';
        title.textContent = '{% trans "Deactivate User" %}';
        message.innerHTML = '{% trans "Are you sure you want to deactivate" %} <strong class="text-navy">' + userName + '</strong>?<br><span class="text-sm text-slate-500">{% trans "This user will not be able to log in until reactivated." %}</span>';
        btn.className = 'px-4 py-2 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition';
    } else {
        header.className = 'bg-green-600 text-white px-6 py-4 flex justify-between items-center';
        title.textContent = '{% trans "Activate User" %}';
        message.innerHTML = '{% trans "Are you sure you want to activate" %} <strong class="text-navy">' + userName + '</strong>?<br><span class="text-sm text-slate-500">{% trans "This user will be able to log in immediately." %}</span>';
        btn.className = 'px-4 py-2 bg-green-600 text-white rounded-xl font-semibold hover:bg-green-700 transition';
    }

    showModal('toggleUserModal');
    lucide.createIcons();
}

function confirmToggleUser() {
    const btn = document.getElementById('confirmToggleBtn');
    const passwordInput = document.getElementById('toggleAdminPassword');
    const passwordError = document.getElementById('togglePasswordError');
    const password = passwordInput.value.trim();

    if (!password) {
        passwordError.textContent = '{% trans "Password is required." %}';
        passwordError.classList.remove('hidden');
        return;
    }

    passwordError.classList.add('hidden');
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin inline"></i> {% trans "Processing..." %}';

    fetch(`/config/users/${toggleUserId}/toggle-active/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify({ password: password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeModal('toggleUserModal');
            document.getElementById('toggleSuccessMessage').textContent = data.message;
            showModal('toggleSuccessModal');
            lucide.createIcons();
        } else {
            passwordError.textContent = data.error || '{% trans "An error occurred." %}';
            passwordError.classList.remove('hidden');
        }
    })
    .catch(error => {
        passwordError.textContent = '{% trans "Network error. Please try again." %}';
        passwordError.classList.remove('hidden');
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '{% trans "Confirm" %}';
    });
}

function closeToggleSuccess() {
    closeModal('toggleSuccessModal');
    window.location.reload();
}
</script>
{% endblock %}
