{% extends "base.html" %}
{% load static %}
{% load core_tags %}

{% block content %}
<div class="container py-5">
    <div class="mb-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'event_list' %}">Events</a></li>
                <li class="breadcrumb-item"><a href="{% url 'event_detail' event.id %}">{{ event.name|default:event.event_type }}</a></li>
                <li class="breadcrumb-item active" aria-current="page">Match Participants</li>
            </ol>
        </nav>
        <h1 class="h2 mb-0">Match Participants for {{ event.name|default:event.event_type }}</h1>
        <p class="text-muted">File: {{ file_name }}</p>
    </div>

    {% if unmatched_rows %}
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0 py-3">
                <h5 class="mb-0 fw-bold">Unmatched Participants ({{ unmatched_rows|length }})</h5>
                <p class="text-muted mb-0">Manually match these participants to existing voters. If a voter is matched, their email will be updated with the one from the file, and they will be added to the event.</p>
            </div>
            <form method="POST" action="{% url 'match_participants' event.id %}">
                {% csrf_token %}
                <div class="card-body">
                    {% for row_data in unmatched_rows %}
                        <div class="mb-4 p-3 border rounded bg-light">
                            <div class="row mb-2">
                                <div class="col-12 mb-2">
                                    <strong>From File (Name):</strong> {{ row_data.row_data|get_item:name_column|default:"N/A" }}
                                </div>
                                <div class="col-md-6">
                                    <strong>From File (Email):</strong> {{ row_data.row_data|get_item:email_column|default:"N/A" }}
                                </div>
                                <div class="col-md-6">
                                    <strong>From File (Status):</strong> {{ row_data.row_data|get_item:participation_status_column|default:"N/A" }}
                                </div>
                                <div class="col-md-6">
                                    <strong>From File (Phone):</strong> {{ row_data.row_data|get_item:phone_column|default:"N/A" }}
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Match to Voter:</label>
                                <input type="text" class="form-control voter-search-input" data-row-index="{{ row_data.original_row_index }}" placeholder="Search voter by name or ID..." autocomplete="off">
                                <div class="list-group voter-search-results mt-1 shadow-sm d-none" style="max-height: 200px; overflow-y: auto; position: absolute; z-index: 1000; width: auto;"></div>
                                <div id="selectedVoterDisplay_{{ row_data.original_row_index }}" class="mt-2 d-none">
                                    <div class="alert alert-info py-2 px-3 mb-0 d-flex justify-content-between align-items-center rounded-3 border-0">
                                        <span class="voter-name-display fw-semibold"></span>
                                        <button type="button" class="btn-close small clear-selected-voter" data-row-index="{{ row_data.original_row_index }}"></button>
                                    </div>
                                </div>
                                <input type="hidden" name="voter_match_{{ row_data.original_row_index }}" id="voter_id_hidden_{{ row_data.original_row_index }}">
                            </div>
                        </div>
                    {% endfor %}
                </div>
                <div class="card-footer bg-light border-0 d-flex justify-content-end py-3">
                    <button type="submit" class="btn btn-primary rounded-pill px-4 shadow-sm">Save Matches & Continue</button>
                </div>
            </form>
        </div>
    {% else %}
        <div class="alert alert-success" role="alert">
            All participants have been successfully processed or no unmatched participants were found.
        </div>
        <a href="{% url 'event_detail' event.id %}" class="btn btn-primary">Back to Event Details</a>
    {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInputs = document.querySelectorAll('.voter-search-input');

    searchInputs.forEach(searchInput => {
        let debounceTimer;
        const rowIndex = searchInput.dataset.rowIndex;
        const resultsContainer = searchInput.nextElementSibling; // The div for results
        const hiddenVoterId = document.getElementById(`voter_id_hidden_${rowIndex}`);
        const selectedDisplay = document.getElementById(`selectedVoterDisplay_${rowIndex}`);
        const voterNameDisplay = selectedDisplay.querySelector('.voter-name-display');
        const clearBtn = selectedDisplay.querySelector('.clear-selected-voter');

        searchInput.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            const query = this.value.trim();
            
            if (query.length < 2) {
                resultsContainer.classList.add('d-none');
                return;
            }
            
            debounceTimer = setTimeout(() => {
                fetch(`/voters/search/json/?q=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        resultsContainer.innerHTML = '';
                        if (data.results && data.results.length > 0) {
                            data.results.forEach(voter => {
                                const btn = document.createElement('button');
                                btn.type = 'button';
                                btn.className = 'list-group-item list-group-item-action py-2';
                                btn.innerHTML = `<div class="fw-bold text-dark">${voter.text}</div><div class="small text-muted">${voter.address || "No address"} | ${voter.phone || "No phone"}</div>`;
                                btn.addEventListener('click', () => {
                                    selectVoter(voter.id, voter.text, voter.address, voter.phone, rowIndex, searchInput, resultsContainer, hiddenVoterId, selectedDisplay, voterNameDisplay);
                                });
                                resultsContainer.appendChild(btn);
                            });
                            resultsContainer.classList.remove('d-none');
                            // Adjust width of results container to match input width
                            resultsContainer.style.width = `${searchInput.offsetWidth}px`;
                        } else {
                            const div = document.createElement('div');
                            div.className = 'list-group-item text-muted small py-2';
                            div.textContent = 'No results found';
                            resultsContainer.appendChild(div);
                            resultsContainer.classList.remove('d-none');
                        }
                    });
            }, 300);
        });

        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                hiddenVoterId.value = '';
                voterNameDisplay.textContent = '';
                selectedDisplay.classList.add('d-none');
                searchInput.parentElement.classList.remove('d-none');
                searchInput.value = '';
                searchInput.classList.remove('d-none');
                resultsContainer.classList.add('d-none');
            });
        }

        // Hide results when clicking outside
        document.addEventListener('click', function(e) {
            if (!resultsContainer.contains(e.target) && e.target !== searchInput) {
                resultsContainer.classList.add('d-none');
            }
        });
    });

    function selectVoter(id, text, address, phone, rowIndex, searchInput, resultsContainer, hiddenVoterId, selectedDisplay, voterNameDisplay) {
        hiddenVoterId.value = id;
        voterNameDisplay.innerHTML = `<div>${text}</div><div class="small fw-normal text-muted">${address || ""} ${phone ? "• " + phone : ""}</div>`;
        selectedDisplay.classList.remove('d-none');
        searchInput.classList.add('d-none'); // Hide the search input after selection
        resultsContainer.classList.add('d-none');
    }
});
</script>

{% endblock %}