<!--
Searchable Dropdown Component

A dropdown with search/filter capabilities using Alpine.js.

Usage:
    {% include 'nitro/components/searchable_dropdown.html' with
        field_name='tenant_id'
        label='Select Tenant'
        options=tenants
        display_field='full_name'
        value_field='id'
        placeholder='Search tenants...'
        required=True
    %}

Required Parameters:
- field_name: Name for the hidden input (e.g., 'tenant_id')
- options: List of objects to choose from

Optional Parameters:
- label: Field label (default: '')
- display_field: Object field to display (default: 'name')
- value_field: Object field for value (default: 'id')
- placeholder: Search placeholder (default: 'Search...')
- required: Whether field is required (default: False)
- help_text: Optional help text below field
- current_value: Pre-selected value
- current_display: Pre-selected display text
-->

{% load nitro_tags %}

<div x-data="{
    open: false,
    search: '',
    selected: {{ current_value|default:'null' }},
    selectedDisplay: '{{ current_display|default:'' }}',
    options: {{ options|safe }},

    get filteredOptions() {
        if (!this.search) return this.options;
        const term = this.search.toLowerCase();
        return this.options.filter(opt => {
            const display = opt.{{ display_field|default:'name' }};
            return display && display.toString().toLowerCase().includes(term);
        });
    },

    selectOption(option) {
        this.selected = option.{{ value_field|default:'id' }};
        this.selectedDisplay = option.{{ display_field|default:'name' }};
        this.open = false;
        this.search = '';
        // Trigger change event for Nitro binding
        this.$refs.hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
    },

    clearSelection() {
        this.selected = null;
        this.selectedDisplay = '';
        this.$refs.hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
    }
}"
     @click.away="open = false"
     class="relative">

    <!-- Label -->
    {% if label %}
    <label class="block text-sm font-medium text-gray-700 mb-1">
        {{ label }}{% if required %} *{% endif %}
    </label>
    {% endif %}

    <!-- Hidden Input (for form submission) -->
    <input type="hidden"
           x-ref="hiddenInput"
           name="{{ field_name }}"
           {% if nitro_model %}{% nitro_model nitro_model %}{% endif %}
           :value="selected">

    <!-- Trigger Button -->
    <button type="button"
            @click="open = !open"
            class="w-full relative rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-left shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            :class="{ 'border-red-300': {{ required|yesno:'true,false' }} && !selected }">

        <span class="block truncate" x-text="selectedDisplay || '{{ placeholder|default:'Select...' }}'"></span>

        <!-- Dropdown Arrow -->
        <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
            <svg class="h-5 w-5 text-gray-400 transition-transform" :class="{ 'rotate-180': open }" 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"></path>
            </svg>
        </span>

        <!-- Clear Button (when selected) -->
        <button type="button"
                x-show="selected"
                @click.stop="clearSelection()"
                class="absolute inset-y-0 right-8 flex items-center pr-2 text-gray-400 hover:text-gray-600">
            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </button>
    </button>

    <!-- Dropdown Panel -->
    <div x-show="open"
         x-transition:enter="transition ease-out duration-100"
         x-transition:enter-start="opacity-0 scale-95"
         x-transition:enter-end="opacity-100 scale-100"
         x-transition:leave="transition ease-in duration-75"
         x-transition:leave-start="opacity-100 scale-100"
         x-transition:leave-end="opacity-0 scale-95"
         class="absolute z-50 mt-1 w-full rounded-lg bg-white shadow-lg border border-gray-200"
         style="display: none;">

        <!-- Search Input -->
        <div class="p-2 border-b border-gray-200">
            <input type="text"
                   x-model="search"
                   @click.stop
                   placeholder="{{ placeholder|default:'Search...' }}"
                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-2">
        </div>

        <!-- Options List -->
        <ul class="max-h-60 overflow-auto py-1">
            <template x-for="option in filteredOptions" :key="option.{{ value_field|default:'id' }}">
                <li @click="selectOption(option)"
                    class="cursor-pointer select-none px-4 py-2 text-sm hover:bg-blue-50 hover:text-blue-900"
                    :class="{ 'bg-blue-100 text-blue-900 font-medium': selected === option.{{ value_field|default:'id' }} }">
                    <span x-text="option.{{ display_field|default:'name' }}"></span>

                    <!-- Checkmark for selected -->
                    <span x-show="selected === option.{{ value_field|default:'id' }}" class="float-right">
                        <svg class="h-5 w-5 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                        </svg>
                    </span>
                </li>
            </template>

            <!-- Empty State -->
            <li x-show="filteredOptions.length === 0" class="px-4 py-6 text-center text-sm text-gray-500">
                No results found
            </li>
        </ul>
    </div>

    <!-- Help Text -->
    {% if help_text %}
    <p class="mt-1 text-xs text-gray-500">{{ help_text }}</p>
    {% endif %}
</div>
