{% load static %}

<form method="post" 
      class="space-y-6" 
      x-data="{ 
          submitting: false,
          manufacturerSearchTerm: '',
          setManufacturerModal(value, term = '') {
              const parentForm = document.querySelector('[x-data]');
              if (parentForm) {
                  const parentData = Alpine.$data(parentForm);
                  if (parentData && parentData.setManufacturerModal) {
                      parentData.setManufacturerModal(value, term);
                  }
              }
          }
      }"
      @submit.prevent="
        if (!submitting) {
            submitting = true;
            const formData = new FormData($event.target);
            htmx.ajax('POST', '/rides/models/create/', {
                values: Object.fromEntries(formData),
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                }
            }).then(response => {
                if (response.detail) {
                    const data = JSON.parse(response.detail.xhr.response);
                    selectRideModel(data.id, data.name);
                }
                const parentForm = document.querySelector('[x-data]');
                if (parentForm) {
                    const parentData = Alpine.$data(parentForm);
                    if (parentData && parentData.setRideModelModal) {
                        parentData.setRideModelModal(false);
                    }
                }
            }).finally(() => {
                submitting = false;
            });
        }">
    {% csrf_token %}
    
    <div id="ride-model-notification"></div>
    
    <div class="space-y-6">
        <!-- Name -->
        <div>
            <label for="{{ form.name.id_for_label }}" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                {{ form.name.label }}{% if form.name.field.required %} *{% endif %}
            </label>
            <input type="text"
                   name="name"
                   id="{{ form.name.id_for_label }}"
                   class="w-full border-gray-300 rounded-lg form-input dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                   required>
        </div>

        <!-- Manufacturer Search -->
        <div>
            <label for="{{ form.manufacturer_search.id_for_label }}" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                {{ form.manufacturer_search.label }}
            </label>
            <div class="relative">
                <div id="manufacturer-notification" class="mb-2"></div>
                <div class="flex gap-2">
                    <div class="flex-grow">
                        <input type="text" 
                               id="{{ form.manufacturer_search.id_for_label }}"
                               name="manufacturer_search"
                               class="w-full border-gray-300 rounded-lg form-input dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                               placeholder="Search for a manufacturer..."
                               hx-get="/rides/search/manufacturers/"
                               hx-trigger="click, input changed delay:200ms"
                               hx-target="#manufacturer-search-results"
                               autocomplete="off"
                               @input="manufacturerSearchTerm = $event.target.value"
                               {% if prefilled_manufacturer %}
                               value="{{ prefilled_manufacturer.name }}"
                               readonly
                               {% endif %}>
                    </div>
                    {% if not prefilled_manufacturer and not create_ride_model %}
                    <button type="button"
                            class="px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600"
                            @click.prevent="setManufacturerModal(true, manufacturerSearchTerm)">
                        <i class="fas fa-plus"></i>
                    </button>
                    {% endif %}
                </div>
                <div id="manufacturer-search-results" class="absolute z-50 w-full"></div>
            </div>
            <input type="hidden" 
                   name="manufacturer" 
                   id="{{ form.manufacturer.id_for_label }}" 
                   {% if prefilled_manufacturer %}
                   value="{{ prefilled_manufacturer.id }}"
                   {% endif %}>
        </div>

        <!-- Category -->
        <div>
            <label for="{{ form.category.id_for_label }}" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                {{ form.category.label }}{% if form.category.field.required %} *{% endif %}
            </label>
            <select name="category"
                    id="{{ form.category.id_for_label }}"
                    class="w-full border-gray-300 rounded-lg form-select dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                    required>
                {% for value, label in form.category.field.choices %}
                    <option value="{{ value }}">{{ label }}</option>
                {% endfor %}
            </select>
        </div>

        <!-- Description -->
        <div>
            <label for="{{ form.description.id_for_label }}" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                {{ form.description.label }}{% if form.description.field.required %} *{% endif %}
            </label>
            <textarea name="description"
                      id="{{ form.description.id_for_label }}"
                      class="w-full border-gray-300 rounded-lg form-textarea dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                      rows="4"></textarea>
        </div>

        {% if not user.is_privileged %}
        <!-- Reason and Source for non-privileged users -->
        <div>
            <label for="reason" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Reason for Addition *
            </label>
            <textarea name="reason"
                      id="reason"
                      class="w-full border-gray-300 rounded-lg form-textarea dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                      rows="3"
                      required
                      placeholder="Please explain why you're adding this ride model and provide any relevant details."></textarea>
        </div>
        <div>
            <label for="source" class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Source (Optional)
            </label>
            <input type="text"
                   name="source"
                   id="source"
                   class="w-full border-gray-300 rounded-lg form-input dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                   placeholder="URL or reference for this information">
        </div>
        {% endif %}
    </div>

    <div class="flex justify-end mt-6 space-x-3">
        {% if modal %}
            <button type="button"
                    @click="$dispatch('close-ride-model-modal')"
                    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-white dark:border-gray-600 dark:hover:bg-gray-600">
                Cancel
            </button>
        {% endif %}
        <button type="submit"
                :disabled="submitting"
                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-lg hover:bg-blue-700 dark:hover:bg-blue-500 disabled:opacity-50">
            <span x-show="!submitting">Create Ride Model</span>
            <span x-show="submitting">Creating...</span>
        </button>
    </div>
</form>

<script>
function selectManufacturer(manufacturerId, manufacturerName) {
    // Update the hidden manufacturer field
    document.getElementById('id_manufacturer').value = manufacturerId;
    // Update the search input with the manufacturer name
    document.getElementById('id_manufacturer_search').value = manufacturerName;
    // Clear the search results
    document.getElementById('manufacturer-search-results').innerHTML = '';
}

// Close search results when clicking outside
document.addEventListener('click', function(event) {
    // Get the parent form element that contains the Alpine.js data
    const formElement = event.target.closest('form[x-data]');
    if (!formElement) return;

    // Get Alpine.js data from the form
    const formData = formElement.__x.$data;
    
    // Don't handle clicks if manufacturer modal is open
    if (formData.showManufacturerModal) {
        return;
    }

    const searchResults = [
        { input: 'id_manufacturer_search', results: 'manufacturer-search-results' }
    ];
    
    searchResults.forEach(function(item) {
        const input = document.getElementById(item.input);
        const results = document.getElementById(item.results);
        if (results && !results.contains(event.target) && event.target !== input) {
            results.innerHTML = '';
        }
    });
});

// Initialize form with any pre-filled values
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('id_ride_model_search');
    if (searchInput && searchInput.value) {
        document.getElementById('id_name').value = searchInput.value;
    }
});
</script>
