{# app/templates/admin/admin-user-edit.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/alerts.html' import loading_state %}
{% from 'shared/macros/headers.html' import edit_page_header %}
{% from 'shared/macros/modals.html' import confirm_modal_dynamic %}

{% block title %}Edit Admin User{% endblock %}

{% block alpine_data %}adminUserEditPage(){% endblock %}

{% block content %}
{% call edit_page_header('Edit Admin User', '/admin/admin-users', subtitle_show='adminUser', back_label='Back to Admin Users') %}
    @<span x-text="adminUser?.username"></span>
{% endcall %}

{{ loading_state('Loading admin user...', show_condition='loading') }}

<!-- Edit Content -->
<div x-show="!loading && adminUser">
    <!-- Quick Actions Card -->
    <div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
        <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
            Quick Actions
        </h3>
        <div class="flex flex-wrap items-center gap-3">
            <!-- Toggle Active Status -->
            <button
                @click="showToggleStatusModal = true"
                :disabled="saving || adminUser?.id === currentUserId"
                class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 rounded-lg focus:outline-none disabled:opacity-50"
                :class="adminUser?.is_active ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700'"
                :title="adminUser?.id === currentUserId ? 'Cannot deactivate yourself' : ''">
                <span x-html="$icon(adminUser?.is_active ? 'user-x' : 'user-check', 'w-4 h-4 mr-2')"></span>
                <span x-text="adminUser?.is_active ? 'Deactivate' : 'Activate'"></span>
            </button>

            <!-- Toggle Super Admin -->
            <button
                @click="showToggleSuperAdminModal = true"
                :disabled="saving || (adminUser?.id === currentUserId && adminUser?.role === 'super_admin')"
                class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 rounded-lg focus:outline-none disabled:opacity-50"
                :class="adminUser?.role === 'super_admin' ? 'bg-yellow-600 hover:bg-yellow-700' : 'bg-purple-600 hover:bg-purple-700'"
                :title="adminUser?.id === currentUserId && adminUser?.role === 'super_admin' ? 'Cannot demote yourself' : ''">
                <span x-html="$icon(adminUser?.role === 'super_admin' ? 'shield-x' : 'shield-check', 'w-4 h-4 mr-2')"></span>
                <span x-text="adminUser?.role === 'super_admin' ? 'Demote from Super Admin' : 'Promote to Super Admin'"></span>
            </button>

            <!-- Status Badges -->
            <div class="ml-auto flex items-center gap-2">
                <span
                    x-show="adminUser?.role === 'super_admin'"
                    class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-yellow-700 bg-yellow-100 rounded-full dark:bg-yellow-700 dark:text-yellow-100">
                    Super Admin
                </span>
                <span
                    x-show="adminUser?.role !== 'super_admin'"
                    class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-purple-700 bg-purple-100 rounded-full dark:bg-purple-700 dark:text-purple-100">
                    Platform Admin
                </span>
                <span
                    x-show="adminUser?.is_active"
                    class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                    Active
                </span>
                <span
                    x-show="!adminUser?.is_active"
                    class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
                    Inactive
                </span>
            </div>
        </div>
    </div>

    <!-- Admin Info Card (Editable) -->
    <div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                Admin Information
            </h3>
            <span class="text-xs text-gray-500 dark:text-gray-400" x-text="'ID: ' + adminUser?.id"></span>
        </div>
        <form @submit.prevent="saveProfile()">
            <div class="grid gap-6 md:grid-cols-2">
                <!-- Left Column -->
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Username</label>
                        <input
                            type="text"
                            x-model="editForm.username"
                            class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-input"
                            required
                            minlength="3"
                        >
                        <p x-show="errors.username" x-text="errors.username" class="mt-1 text-xs text-red-600 dark:text-red-400"></p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Email</label>
                        <input
                            type="email"
                            x-model="editForm.email"
                            class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-input"
                            required
                        >
                        <p x-show="errors.email" x-text="errors.email" class="mt-1 text-xs text-red-600 dark:text-red-400"></p>
                    </div>
                </div>
                <!-- Right Column -->
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">First Name</label>
                        <input
                            type="text"
                            x-model="editForm.first_name"
                            class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-input"
                            placeholder="First name"
                        >
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Last Name</label>
                        <input
                            type="text"
                            x-model="editForm.last_name"
                            class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-input"
                            placeholder="Last name"
                        >
                    </div>
                </div>
            </div>
            <div class="flex items-center justify-end mt-6 gap-3">
                <span x-show="profileDirty" class="text-xs text-orange-600 dark:text-orange-400">Unsaved changes</span>
                <button
                    type="submit"
                    :disabled="saving || !profileDirty"
                    class="flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50 transition-colors">
                    <span x-show="!saving">Save Changes</span>
                    <span x-show="saving" class="flex items-center">
                        <span x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
                        Saving...
                    </span>
                </button>
            </div>
        </form>
    </div>

    <!-- Platform Assignments Card (Only for Platform Admins) -->
    <template x-if="adminUser?.role !== 'super_admin'">
        <div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Platform Assignments
                </h3>
                <button
                    @click="openPlatformModal()"
                    :disabled="saving || availablePlatformsForAssignment.length === 0"
                    class="flex items-center px-3 py-1.5 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50">
                    <span x-html="$icon('plus', 'w-4 h-4 mr-1')"></span>
                    Add Platform
                </button>
            </div>

            <!-- Assigned Platforms List -->
            <div x-show="adminUser?.platforms?.length > 0" class="space-y-2">
                <template x-for="platform in adminUser?.platforms" :key="platform.id">
                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg dark:bg-gray-700">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center mr-3">
                                <span class="text-lg font-bold text-purple-600 dark:text-purple-400" x-text="platform.code.charAt(0).toUpperCase()"></span>
                            </div>
                            <div>
                                <p class="font-medium text-gray-800 dark:text-gray-200" x-text="platform.name"></p>
                                <p class="text-sm text-gray-500 dark:text-gray-400" x-text="platform.code"></p>
                            </div>
                        </div>
                        <button
                            @click="removePlatform(platform.id)"
                            :disabled="saving || adminUser?.platforms?.length <= 1"
                            class="p-2 text-red-600 hover:bg-red-100 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
                            :title="adminUser?.platforms?.length <= 1 ? 'Must have at least one platform' : 'Remove platform'">
                            <span x-html="$icon('x', 'w-5 h-5')"></span>
                        </button>
                    </div>
                </template>
            </div>

            <!-- No Platforms Message -->
            <div x-show="!adminUser?.platforms?.length" class="text-center py-6">
                <span x-html="$icon('exclamation', 'mx-auto h-12 w-12 text-gray-400')"></span>
                <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">No platforms assigned</p>
            </div>

            <p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
                <span x-html="$icon('information-circle', 'w-4 h-4 inline mr-1')"></span>
                Platform admins must be assigned to at least one platform.
            </p>
        </div>
    </template>

    <!-- Super Admin Notice -->
    <template x-if="adminUser?.role === 'super_admin'">
        <div class="px-4 py-3 mb-6 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
            <div class="flex items-center">
                <span x-html="$icon('shield-check', 'w-6 h-6 text-yellow-600 dark:text-yellow-400 mr-3')"></span>
                <div>
                    <h4 class="font-medium text-yellow-800 dark:text-yellow-200">Super Admin Access</h4>
                    <p class="text-sm text-yellow-700 dark:text-yellow-300">This user has full access to all platforms and administrative functions.</p>
                </div>
            </div>
        </div>
    </template>

    <!-- Danger Zone Card -->
    <div class="px-4 py-3 bg-white rounded-lg shadow-md dark:bg-gray-800 border border-red-200 dark:border-red-800">
        <h3 class="mb-4 text-lg font-semibold text-red-700 dark:text-red-400">
            Danger Zone
        </h3>
        <div class="flex flex-wrap items-center gap-3">
            <!-- Delete Admin User Button -->
            <button
                @click="showDeleteModal = true"
                :disabled="saving || adminUser?.id === currentUserId"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white transition-colors duration-150 bg-red-600 border border-transparent rounded-lg hover:bg-red-700 focus:outline-none focus:shadow-outline-red disabled:opacity-50"
                :title="adminUser?.id === currentUserId ? 'Cannot delete yourself' : 'Delete this admin user'">
                <span x-html="$icon('delete', 'w-4 h-4 mr-2')"></span>
                Delete Admin User
            </button>
        </div>
        <p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
            <span x-html="$icon('exclamation', 'w-4 h-4 inline mr-1 text-red-500')"></span>
            Deleting an admin user is permanent and cannot be undone.
        </p>
    </div>
</div>

<!-- Platform Assignment Modal -->
<div
    x-show="showPlatformModal"
    x-cloak
    class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
    @click.self="showPlatformModal = false"
    @keydown.escape.window="showPlatformModal = false">
    <div class="w-full max-w-md p-6 bg-white rounded-lg shadow-xl dark:bg-gray-800">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                Assign Platform
            </h3>
            <button
                @click="showPlatformModal = false"
                class="p-1 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <span x-html="$icon('x', 'w-5 h-5')"></span>
            </button>
        </div>

        <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
                Select Platform
            </label>
            <select
                x-model="selectedPlatformId"
                class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-select">
                <option value="">Choose a platform...</option>
                <template x-for="platform in availablePlatformsForAssignment" :key="platform.id">
                    <option :value="platform.id" x-text="`${platform.name} (${platform.code})`"></option>
                </template>
            </select>
        </div>

        <div x-show="availablePlatformsForAssignment.length === 0" class="mb-4 p-3 bg-gray-100 dark:bg-gray-700 rounded-lg">
            <p class="text-sm text-gray-600 dark:text-gray-400">
                All available platforms have been assigned to this admin.
            </p>
        </div>

        <div class="flex justify-end gap-3">
            <button
                @click="showPlatformModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600">
                Cancel
            </button>
            <button
                @click="assignPlatform(selectedPlatformId)"
                :disabled="!selectedPlatformId || saving"
                class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50">
                <span x-show="!saving">Assign Platform</span>
                <span x-show="saving" class="flex items-center">
                    <span x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
                    Assigning...
                </span>
            </button>
        </div>
    </div>
</div>

<!-- Remove Platform Confirmation Modal -->
{{ confirm_modal_dynamic(
    'removePlatformModal',
    'Remove Platform',
    "'Are you sure you want to remove \"' + (platformToRemove?.name || '') + '\" from this admin?'",
    'confirmRemovePlatform()',
    'showRemovePlatformModal',
    'Remove',
    'Cancel',
    'warning'
) }}

<!-- Toggle Super Admin Confirmation Modal -->
{{ confirm_modal_dynamic(
    'toggleSuperAdminModal',
    'Toggle Super Admin',
    "'Are you sure you want to ' + (adminUser?.role === 'super_admin' ? 'demote' : 'promote') + ' \"' + (adminUser?.username || '') + '\" ' + (adminUser?.role === 'super_admin' ? 'from' : 'to') + ' super admin?'",
    'toggleSuperAdmin()',
    'showToggleSuperAdminModal',
    'Confirm',
    'Cancel',
    'warning'
) }}

<!-- Toggle Status Confirmation Modal -->
{{ confirm_modal_dynamic(
    'toggleStatusModal',
    'Toggle User Status',
    "'Are you sure you want to ' + (adminUser?.is_active ? 'deactivate' : 'activate') + ' \"' + (adminUser?.username || '') + '\"?'",
    'toggleStatus()',
    'showToggleStatusModal',
    'Confirm',
    'Cancel',
    'warning'
) }}

<!-- Delete Admin User Confirmation Modal (Step 1) -->
{{ confirm_modal_dynamic(
    'deleteAdminUserModal',
    'Delete Admin User',
    "'Are you sure you want to delete admin user \"' + (adminUser?.username || '') + '\"? This action cannot be undone.'",
    'confirmDeleteStep()',
    'showDeleteModal',
    'Delete',
    'Cancel',
    'danger'
) }}

<!-- Delete Admin User Final Confirmation Modal (Step 2) -->
{{ confirm_modal_dynamic(
    'deleteAdminUserFinalModal',
    'Final Confirmation',
    "'FINAL CONFIRMATION: Are you absolutely sure you want to permanently delete \"' + (adminUser?.username || '') + '\"?'",
    'deleteAdminUser()',
    'showDeleteFinalModal',
    'Permanently Delete',
    'Cancel',
    'danger'
) }}
{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('tenancy_static', path='admin/js/admin-user-edit.js') }}"></script>
{% endblock %}
