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

{% block title %}Edit Merchant{% endblock %}

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

{% block content %}
{% call edit_page_header('Edit Merchant', '/admin/merchants', subtitle_show='merchant', back_label='Back to Merchants') %}
    <span x-text="merchant?.name"></span>
{% endcall %}

{{ loading_state('Loading merchant...', show_condition='loadingMerchant') }}

<!-- Edit Form -->
<div x-show="!loadingMerchant && merchant">
    <!-- 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">
            <button
                @click="showToggleVerificationModal = true"
                :disabled="saving"
                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 focus:shadow-outline-purple disabled:opacity-50"
                :class="{ 'bg-orange-600 hover:bg-orange-700': merchant && merchant.is_verified, 'bg-green-600 hover:bg-green-700': merchant && !merchant.is_verified }">
                <span x-html="$icon(merchant?.is_verified ? 'x-circle' : 'badge-check', 'w-4 h-4 mr-2')"></span>
                <span x-text="merchant?.is_verified ? 'Unverify Merchant' : 'Verify Merchant'"></span>
            </button>

            <button
                @click="showToggleActiveModal = true"
                :disabled="saving"
                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 focus:shadow-outline-purple disabled:opacity-50"
                :class="{ 'bg-red-600 hover:bg-red-700': merchant && merchant.is_active, 'bg-green-600 hover:bg-green-700': merchant && !merchant.is_active }">
                <span x-html="$icon(merchant?.is_active ? 'lock-closed' : 'lock-open', 'w-4 h-4 mr-2')"></span>
                <span x-text="merchant?.is_active ? 'Deactivate' : 'Activate'"></span>
            </button>

            <!-- Status Badges -->
            <div class="ml-auto flex items-center gap-2">
                <span
                    x-show="merchant?.is_verified"
                    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">
                    <span x-html="$icon('badge-check', 'w-3 h-3 mr-1')"></span>
                    Verified
                </span>
                <span
                    x-show="!merchant?.is_verified"
                    class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">
                    <span x-html="$icon('clock', 'w-3 h-3 mr-1')"></span>
                    Pending
                </span>
                <span
                    x-show="merchant?.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="!merchant?.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>

    <!-- Form Card -->
    <form @submit.prevent="handleSubmit" class="px-4 py-3 mb-8 bg-white rounded-lg shadow-md dark:bg-gray-800">
        <div class="grid gap-6 mb-8 md:grid-cols-2">
            <!-- Left Column: Basic Info -->
            <div>
                <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Basic Information
                </h3>

                <!-- Merchant ID (readonly) -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Merchant ID
                    </span>
                    <input
                        type="text"
                        :value="merchant?.id"
                        disabled
                        class="block w-full mt-1 text-sm bg-gray-100 border-gray-300 rounded-md dark:bg-gray-700 dark:text-gray-400 dark:border-gray-600 cursor-not-allowed"
                    >
                    <span class="text-xs text-gray-600 dark:text-gray-400 mt-1">
                        System-generated identifier
                    </span>
                </label>

                <!-- Name -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Merchant Name <span class="text-red-600">*</span>
                    </span>
                    <input
                        type="text"
                        x-model="formData.name"
                        required
                        maxlength="255"
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-input"
                        :class="{ 'border-red-600 focus:border-red-400 focus:shadow-outline-red': errors.name }"
                    >
                    <span x-show="errors.name" class="text-xs text-red-600 dark:text-red-400 mt-1" x-text="errors.name"></span>
                </label>

                <!-- Description -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Description
                    </span>
                    <textarea
                        x-model="formData.description"
                        rows="3"
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-textarea"
                    ></textarea>
                </label>
            </div>

            <!-- Right Column: Contact Info -->
            <div>
                <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Contact Information
                </h3>

                <!-- Owner Info (readonly) -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Owner
                    </span>
                    <input
                        type="text"
                        :value="merchant?.owner_username ? merchant.owner_username + ' (' + merchant.owner_email + ')' : 'User ID: ' + merchant?.owner_user_id"
                        disabled
                        class="block w-full mt-1 text-sm bg-gray-100 border-gray-300 rounded-md dark:bg-gray-700 dark:text-gray-400 dark:border-gray-600 cursor-not-allowed"
                    >
                    <span class="text-xs text-gray-600 dark:text-gray-400 mt-1">
                        Use "Transfer Ownership" in More Actions to change
                    </span>
                </label>

                <!-- Contact Email -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Contact Email <span class="text-red-600">*</span>
                    </span>
                    <input
                        type="email"
                        x-model="formData.contact_email"
                        required
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-input"
                        :class="{ 'border-red-600 focus:border-red-400 focus:shadow-outline-red': errors.contact_email }"
                    >
                    <span class="text-xs text-gray-600 dark:text-gray-400 mt-1">
                        Public business contact email
                    </span>
                    <span x-show="errors.contact_email" class="text-xs text-red-600 dark:text-red-400 mt-1" x-text="errors.contact_email"></span>
                </label>

                <!-- Phone -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Phone
                    </span>
                    <input
                        type="tel"
                        x-model="formData.contact_phone"
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-input"
                    >
                </label>

                <!-- Website -->
                <label class="block mb-4 text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Website
                    </span>
                    <input
                        type="url"
                        x-model="formData.website"
                        :disabled="saving"
                        placeholder="https://example.com"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-input"
                    >
                </label>
            </div>
        </div>

        <!-- Business Details -->
        <div class="mb-8">
            <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
                Business Details
            </h3>

            <div class="grid gap-6 md:grid-cols-2">
                <!-- Business Address -->
                <label class="block text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Business Address
                    </span>
                    <textarea
                        x-model="formData.business_address"
                        rows="3"
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-textarea"
                    ></textarea>
                </label>

                <!-- Tax Number -->
                <label class="block text-sm">
                    <span class="text-gray-700 dark:text-gray-400">
                        Tax Number
                    </span>
                    <input
                        type="text"
                        x-model="formData.tax_number"
                        :disabled="saving"
                        class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-input"
                    >
                </label>
            </div>
        </div>

        <!-- Merchant Statistics (readonly) -->
        <template x-if="merchant?.store_count !== undefined">
            <div class="mb-8">
                <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Merchant Statistics
                </h3>
                <div class="grid gap-4 md:grid-cols-2">
                    <div class="p-4 bg-gray-50 rounded-lg dark:bg-gray-700">
                        <p class="text-sm text-gray-600 dark:text-gray-400">Total Stores</p>
                        <p class="text-2xl font-semibold text-gray-700 dark:text-gray-200" x-text="merchant.store_count || 0"></p>
                    </div>
                    <div class="p-4 bg-gray-50 rounded-lg dark:bg-gray-700">
                        <p class="text-sm text-gray-600 dark:text-gray-400">Active Stores</p>
                        <p class="text-2xl font-semibold text-gray-700 dark:text-gray-200" x-text="merchant.active_store_count || 0"></p>
                    </div>
                </div>
            </div>
        </template>

        <!-- Save Button -->
        <div class="flex items-center justify-end gap-3 pt-6 border-t dark:border-gray-700">
            <a
                href="/admin/merchants"
                class="px-4 py-2 text-sm font-medium leading-5 text-gray-700 transition-colors duration-150 bg-white border border-gray-300 rounded-lg dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800 hover:border-gray-400 focus:outline-none">
                Cancel
            </a>
            <button
                type="submit"
                :disabled="saving"
                class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple disabled:opacity-50 disabled:cursor-not-allowed">
                <span x-show="!saving">
                    <span x-html="$icon('check', 'w-4 h-4 mr-2 inline')"></span>
                    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>

    <!-- More Actions Section -->
    <div class="px-4 py-3 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">
            More Actions
        </h3>
        <div class="flex flex-wrap gap-3">
            <!-- Transfer Ownership Button -->
            <button
                @click="showTransferOwnershipModal = true"
                :disabled="saving"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white transition-colors duration-150 bg-orange-600 border border-transparent rounded-lg hover:bg-orange-700 focus:outline-none focus:shadow-outline-orange disabled:opacity-50"
            >
                <span x-html="$icon('switch-horizontal', 'w-4 h-4 mr-2')"></span>
                Transfer Ownership
            </button>

            <!-- Delete Merchant Button -->
            <button
                @click="promptDeleteMerchant()"
                :disabled="saving || (merchant?.store_count > 0)"
                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="merchant?.store_count > 0 ? 'Cannot delete merchant with stores' : 'Delete this merchant'"
            >
                <span x-html="$icon('delete', 'w-4 h-4 mr-2')"></span>
                Delete Merchant
            </button>
        </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>
            Ownership transfer affects all stores under this merchant.
            <span x-show="merchant?.store_count > 0" class="text-orange-600 dark:text-orange-400">
                Merchant cannot be deleted while it has stores (<span x-text="merchant?.store_count"></span> stores).
            </span>
        </p>
    </div>

    {{ confirm_modal_dynamic(
        'toggleVerificationModal',
        'Toggle Verification',
        "merchant?.is_verified ? 'Are you sure you want to unverify this merchant?' : 'Are you sure you want to verify this merchant?'",
        'toggleVerification()',
        'showToggleVerificationModal',
        'Confirm',
        'Cancel',
        'warning'
    ) }}

    {{ confirm_modal_dynamic(
        'toggleActiveModal',
        'Toggle Active Status',
        "merchant?.is_active ? 'Are you sure you want to deactivate this merchant? This will affect all stores under this merchant.' : 'Are you sure you want to activate this merchant? This will affect all stores under this merchant.'",
        'toggleActive()',
        'showToggleActiveModal',
        'Confirm',
        'Cancel',
        'warning'
    ) }}

    {{ confirm_modal_dynamic(
        'deleteMerchantModal',
        'Delete Merchant',
        "'Are you sure you want to delete merchant \"' + (merchant?.name || '') + '\"? This action cannot be undone.'",
        'confirmDeleteMerchantStep()',
        'showDeleteMerchantModal',
        'Continue',
        'Cancel',
        'danger'
    ) }}

    {{ confirm_modal_dynamic(
        'deleteMerchantFinalModal',
        'Final Confirmation',
        "'FINAL CONFIRMATION: Delete \"' + (merchant?.name || '') + '\"? This will permanently delete the merchant and all its data.'",
        'deleteMerchant()',
        'showDeleteMerchantFinalModal',
        'Delete Permanently',
        'Cancel',
        'danger'
    ) }}

    {# noqa: FE-004 - Complex form modal with dynamic user search and transfer functionality #}
    <!-- Transfer Ownership Modal -->
    <div
        x-show="showTransferOwnershipModal"
        x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50"
        @keydown.escape.window="showTransferOwnershipModal = false"
    >
        <div
            @click.away="showTransferOwnershipModal = false"
            class="w-full max-w-md bg-white rounded-lg shadow-lg dark:bg-gray-800"
        >
            <!-- Modal Header -->
            <div class="flex items-center justify-between p-4 border-b dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Transfer Merchant Ownership
                </h3>
                <button
                    @click="showTransferOwnershipModal = false"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
                >
                    <span x-html="$icon('x', 'w-5 h-5')"></span>
                </button>
            </div>

            <!-- Modal Body -->
            <div class="p-4">
                <div class="mb-4 p-3 bg-orange-100 border border-orange-300 text-orange-700 rounded-lg dark:bg-orange-900 dark:border-orange-700 dark:text-orange-300">
                    <p class="flex items-start text-sm">
                        <span x-html="$icon('exclamation', 'w-5 h-5 mr-2 flex-shrink-0')"></span>
                        <span>
                            <strong>Warning:</strong> This will transfer ownership of the merchant
                            "<span x-text="merchant?.name"></span>" and all its stores to another user.
                        </span>
                    </p>
                </div>

                <form @submit.prevent="transferOwnership()">
                    <!-- New Owner Search -->
                    <label class="block mb-4 text-sm">
                        <span class="text-gray-700 dark:text-gray-400">
                            New Owner <span class="text-red-600">*</span>
                        </span>
                        {{ search_autocomplete(
                            search_var='userSearchQuery',
                            results_var='userSearchResults',
                            show_dropdown_var='showUserDropdown',
                            loading_var='searchingUsers',
                            disabled_var='transferring',
                            search_action='searchUsers()',
                            select_action='selectUser(item)',
                            selected_check='transferData.new_owner_user_id === item.id',
                            display_field='username',
                            secondary_field='email',
                            placeholder='Search by name or email...',
                            no_results_text='No users found'
                        ) }}
                        {{ selected_item_display(
                            selected_var='selectedUser',
                            display_field='username',
                            secondary_field='email',
                            clear_action='clearSelectedUser()'
                        ) }}
                        <span class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            Current owner: <span x-text="merchant?.owner_username || 'User ID ' + merchant?.owner_user_id"></span>
                        </span>
                        <p x-show="showOwnerError && !transferData.new_owner_user_id" class="mt-1 text-xs text-red-600 dark:text-red-400">
                            <span x-html="$icon('exclamation', 'w-4 h-4 inline mr-1')"></span>
                            Please select a new owner
                        </p>
                    </label>

                    <!-- Transfer Reason -->
                    <label class="block mb-4 text-sm">
                        <span class="text-gray-700 dark:text-gray-400">
                            Reason (optional)
                        </span>
                        <textarea
                            x-model="transferData.transfer_reason"
                            rows="2"
                            :disabled="transferring"
                            placeholder="Enter reason for transfer (for audit log)"
                            class="block w-full mt-1 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 dark:focus:shadow-outline-gray form-textarea"
                        ></textarea>
                    </label>

                    <!-- Confirmation Checkbox -->
                    <label class="flex items-center text-sm">
                        <input
                            type="checkbox"
                            x-model="transferData.confirm_transfer"
                            :disabled="transferring"
                            class="form-checkbox text-purple-600"
                        >
                        <span class="ml-2 text-gray-700 dark:text-gray-400">
                            I confirm I want to transfer ownership
                        </span>
                    </label>
                    <p x-show="showConfirmError && !transferData.confirm_transfer" class="mt-1 mb-4 text-xs text-red-600 dark:text-red-400">
                        <span x-html="$icon('exclamation', 'w-4 h-4 inline mr-1')"></span>
                        Please confirm the transfer by checking the box above
                    </p>
                    <div x-show="!showConfirmError || transferData.confirm_transfer" class="mb-4"></div>

                    <!-- Modal Actions -->
                    <div class="flex justify-end gap-3">
                        <button
                            type="button"
                            @click="showTransferOwnershipModal = false"
                            :disabled="transferring"
                            class="px-4 py-2 text-sm font-medium text-gray-700 transition-colors duration-150 bg-white border border-gray-300 rounded-lg dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800 hover:border-gray-400 focus:outline-none disabled:opacity-50"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="transferring"
                            class="flex items-center px-4 py-2 text-sm font-medium text-white transition-colors duration-150 bg-orange-600 border border-transparent rounded-lg hover:bg-orange-700 focus:outline-none focus:shadow-outline-orange disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <span x-show="!transferring">
                                <span x-html="$icon('switch-horizontal', 'w-4 h-4 mr-2 inline')"></span>
                                Transfer Ownership
                            </span>
                            <span x-show="transferring" class="flex items-center">
                                <span x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
                                Transferring...
                            </span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

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