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

{% block content %}
<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h2">Advanced Voter Search</h1>
        <div class="d-flex gap-2">
            <a href="{% url 'voter_list' %}" class="btn btn-outline-secondary btn-sm">Back to Registry</a>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body p-4">
            <form action="." method="GET" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">First Name</label>
                    {{ form.first_name }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Last Name</label>
                    {{ form.last_name }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Voter ID</label>
                    {{ form.voter_id }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Address</label>
                    {{ form.address }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Birth Month</label>
                    {{ form.birth_month }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">City</label>
                    {{ form.city }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Zip Code</label>
                    {{ form.zip_code }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">District</label>
                    {{ form.district }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Precinct</label>
                    {{ form.precinct }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Email</label>
                    {{ form.email }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Phone Type</label>
                    {{ form.phone_type }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Candidate Support</label>
                    {{ form.candidate_support }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Yard Sign</label>
                    {{ form.yard_sign }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Window Sticker</label>
                    {{ form.window_sticker }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Min Total Donation</label>
                    {{ form.min_total_donation }}
                </div>
                <div class="col-md-4">
                    <label class="form-label small fw-bold text-muted">Max Total Donation</label>
                    {{ form.max_total_donation }}
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="form-check mb-2">
                        {{ form.is_targeted }}
                        <label class="form-check-label ms-1" for="{{ form.is_targeted.id_for_label }}">
                            Targeted Only
                        </label>
                    </div>
                </div>
                <div class="col-12 text-end">
                    <a href="{% url 'voter_advanced_search' %}" class="btn btn-light me-2">Clear Filters</a>
                    <button type="submit" class="btn btn-primary px-4">Search Voters</button>
                </div>
            </form>
        </div>
    </div>

    <form id="bulk-action-form" action="{% url 'export_voters_csv' %}" method="POST">
        {% csrf_token %}
        <!-- Hidden inputs to pass search filters for "Export All" scenario -->
        {% for key, value in request.GET.items %}
            {% if key != 'csrfmiddlewaretoken' and key != 'page' %}
            <input type="hidden" name="filter_{{ key }}" value="{{ value }}">
            {% endif %}
        {% endfor %}

        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3 border-0 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold">Search Results ({{ voters.paginator.count }})</h5>
                {% if can_edit_voter %}
                <div class="d-flex align-items-center">
                    <div id="bulk-actions" class="d-none me-2">
                        <button type="submit" name="action" value="export_selected" class="btn btn-primary btn-sm">
                            <i class="bi bi-file-earmark-spreadsheet me-1"></i> Export Selected
                        </button>
                        <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#bulkCallModal">
                            <i class="bi bi-telephone-plus me-1"></i> Call Selected
                        </button>
                        <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#smsModal">
                            <i class="bi bi-chat-left-text me-1"></i> Send Bulk SMS
                        <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#emailModal">
                            <i class="bi bi-envelope me-1"></i> Send Bulk Email
                        </button>
                        </button>
                    </div>
                    <div>
                        <button type="submit" name="action" value="export_all" class="btn btn-primary btn-sm">
                            <i class="bi bi-file-earmark-spreadsheet me-1"></i> Export All Results
                        </button>
                    </div>
                </div>
                {% endif %}
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0 align-middle">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4" style="width: 40px;">
                                <input type="checkbox" class="form-check-input" id="select-all">
                            </th>
                            <th>Name</th>
                            <th>District</th>
                            <th>Phone</th>
                            <th>Target Voter</th>
                            <th class="pe-4">Supporter</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for voter in voters %}
                        <tr>
                            <td class="ps-4">
                                <input type="checkbox" name="selected_voters" value="{{ voter.id }}" class="form-check-input voter-checkbox">
                            </td>
                            <td>
                                <a href="{% url 'voter_detail' voter.id %}" class="fw-semibold text-primary text-decoration-none d-block">
                                    {{ voter.first_name }} {{ voter.last_name }}
                                </a>
                                <div class="small text-muted">{{ voter.address|default:"No address provided" }}</div>
                            </td>
                            <td><span class="badge bg-light text-dark border">{{ voter.district|default:"-" }}</span></td>
                            <td>
                                {% if voter.phone %}
                                    <div class="d-flex align-items-center mb-1">
                                        <a href="tel:{{ voter.phone }}" class="text-decoration-none text-dark fw-medium me-2">{{ voter.phone }}</a>
                                        <a href="tel:{{ voter.phone }}" class="text-primary me-2" title="Call"><i class="bi bi-telephone" style="font-size: 0.85rem;"></i></a>
                                        <a href="sms:{{ voter.phone }}" class="text-secondary" title="Text"><i class="bi bi-chat-dots" style="font-size: 0.85rem;"></i></a>
                                    </div>
                                    <div class="small text-muted">{{ voter.get_phone_type_display }}</div>
                                {% else %}
                                    -
                                {% endif %}
                                {% if voter.secondary_phone %}
                                    <div class="mt-2">
                                        <div class="d-flex align-items-center mb-1">
                                            <a href="tel:{{ voter.secondary_phone }}" class="text-decoration-none text-muted fw-medium me-2">{{ voter.secondary_phone }}</a>
                                            <a href="tel:{{ voter.secondary_phone }}" class="text-primary me-2" title="Call"><i class="bi bi-telephone" style="font-size: 0.75rem;"></i></a>
                                            <a href="sms:{{ voter.secondary_phone }}" class="text-secondary" title="Text"><i class="bi bi-chat-dots" style="font-size: 0.75rem;"></i></a>
                                        </div>
                                        <div class="small text-muted">{{ voter.get_secondary_phone_type_display }}</div>
                                    </div>
                                {% endif %}
                            </td>
                            <td>
                                {% if voter.is_targeted %}
                                    <span class="badge bg-primary">Yes</span>
                                {% else %}
                                    <span class="badge bg-secondary-subtle text-secondary">No</span>
                                {% endif %}
                            </td>
                            <td class="pe-4">
                                {% if voter.candidate_support == 'supporting' %}
                                    <span class="badge bg-success">Supporting</span>
                                {% elif voter.candidate_support == 'not_supporting' %}
                                    <span class="badge bg-danger">Not Supporting</span>
                                {% else %}
                                    <span class="badge bg-secondary">Unknown</span>
                                {% endif %}
                            </td>
                            <td class="pe-4 text-end">
                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#scheduleCallModal" 
                                        data-voter-id="{{ voter.id }}" 
                                        data-voter-name="{{ voter.first_name }} {{ voter.last_name }}">
                                    <i class="bi bi-telephone-plus"></i>
                                </button>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="7" class="text-center py-5 text-muted">
                                <p class="mb-0">No voters found matching your search criteria.</p>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            
            {% if voters.paginator.num_pages > 1 %}
            <div class="card-footer bg-white border-0 py-3">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center mb-0">
                        {% if voters.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?page=1{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="First">
                                <span aria-hidden="true">&laquo;&laquo;</span>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?page={{ voters.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        {% endif %}

                        <li class="page-item active"><span class="page-link">{{ voters.number }} of {{ voters.paginator.num_pages }}</span></li>

                        {% if voters.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ voters.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?page={{ voters.paginator.num_pages }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Last">
                                <span aria-hidden="true">&raquo;&raquo;</span>
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                </nav>
            </div>
            {% endif %}
        </div>
    </form>
</div>

<!-- Map Modal -->
<div class="modal fade" id="mapModal" tabindex="-1" aria-labelledby="mapModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen p-2 p-md-4">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-header border-0 bg-primary text-white p-3 p-md-4">
                <h5 class="modal-title d-flex align-items-center" id="mapModalLabel">
                    <i class="bi bi-map-fill me-2"></i> Search Results Map
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <div id="map" style="width: 100%; height: 100%; min-height: 500px;"></div>
            </div>
        </div>
    </div>
</div>

<!-- SMS Modal -->
<div class="modal fade" id="smsModal" tabindex="-1" aria-labelledby="smsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold" id="smsModalLabel">Send Bulk SMS</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{% url 'bulk_send_sms' %}" method="POST" id="sms-form">
                {% csrf_token %}
                <div class="modal-body py-4">
                    <p class="small text-muted mb-3">Messages will only be sent to selected voters who have a <strong>Cell Phone</strong> entered. Others will be skipped.</p>
                    <div id="selected-voters-sms-container">
                        <input type="hidden" name="client_time" id="client_time">
                        <!-- Voter IDs will be injected here -->
                    </div>
                    <div class="mb-0">
                        <label for="message_body" class="form-label small fw-bold text-muted">Message Body</label>
                        <textarea class="form-control" id="message_body" name="message_body" rows="4" required placeholder="Type your message here..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4">Send Bulk SMS</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Call Modal -->
<div class="modal fade" id="bulkCallModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">Bulk Schedule Calls</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{% url 'bulk_schedule_calls' %}" method="POST" id="bulk-call-form">
                {% csrf_token %}
                <div class="modal-body py-4">
                    <div id="selected-voters-call-container">
                        <!-- Voter IDs will be injected here -->
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted">Volunteer to call back</label>
                        {{ call_form.volunteer }}
                    </div>
                    <div class="mb-0">
                        <label class="form-label small fw-bold text-muted">Comments</label>
                        {{ call_form.comments }}
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4">Add to Call Queue</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Email Modal -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold" id="emailModalLabel">Send Bulk Email</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{% url "voter_bulk_send_email" %}" method="POST" id="email-form">
                {% csrf_token %}
                <div class="modal-body py-4">
                    <p class="small text-muted mb-3">Emails will be sent to selected voters with an email address on file. Interactions will be logged.</p>
                    <div id="selected-voters-email-container">
                        <!-- Voter IDs will be injected here -->
                    </div>
                    <div class="mb-3">
                        <label for="subject" class="form-label small fw-bold text-muted">Subject</label>
                        <input type="text" class="form-control" id="subject" name="subject" required placeholder="Email subject...">
                    </div>
                    <div class="mb-0">
                        <label for="body" class="form-label small fw-bold text-muted">Message Body</label>
                        <textarea class="form-control" id="body" name="body" rows="6" required placeholder="Type your email body here..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4">Send Bulk Email</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- Individual Schedule Call Modal -->
<div class="modal fade" id="scheduleCallModal" tabindex="-1" aria-labelledby="scheduleCallModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 bg-light">
                <h5 class="modal-title">Schedule Call: <span id="voterNameLabel"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="scheduleCallForm" action="" method="POST">
                {% csrf_token %}
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-medium">Volunteer to call back</label>
                        {{ call_form.volunteer }}
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-medium">Comments</label>
                        {{ call_form.comments }}
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4">Add to Call Queue</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Google Maps JS -->
{% if GOOGLE_MAPS_API_KEY %}
<script src="https://maps.googleapis.com/maps/api/js?key={{ GOOGLE_MAPS_API_KEY }}"></script>
{% endif %}

<script>
    var map;
    var markers = [];
    var mapData = {{ map_data_json|safe|default:"[]" }};

    function initMap() {
        if (!window.google || !window.google.maps) {
            console.error("Google Maps API not loaded");
            return;
        }

        var mapOptions = {
            zoom: 12,
            center: { lat: 41.8781, lng: -87.6298 }, // Default to Chicago
            mapTypeControl: true,
            streetViewControl: true,
            fullscreenControl: true
        };
        map = new google.maps.Map(document.getElementById('map'), mapOptions);
        
        var bounds = new google.maps.LatLngBounds();
        var infowindow = new google.maps.InfoWindow();

        mapData.forEach(function(item) {
            if (item.lat && item.lng) {
                var position = { lat: parseFloat(item.lat), lng: parseFloat(item.lng) };
                var marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: item.voters
                });

                marker.addListener('click', function() {
                    infowindow.setContent('<strong>' + item.voters + '</strong><br>' + item.address);
                    infowindow.open(map, marker);
                });

                markers.push(marker);
                bounds.extend(position);
            }
        });

        if (markers.length > 0) {
            map.fitBounds(bounds);
        }
    }

document.addEventListener('DOMContentLoaded', function() {
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.voter-checkbox');
    const bulkActions = document.getElementById('bulk-actions');

    function updateBulkActionsVisibility() {
        const checkedCount = document.querySelectorAll('.voter-checkbox:checked').length;
        if (bulkActions) {
            if (checkedCount > 0) {
                bulkActions.classList.remove('d-none');
            } else {
                bulkActions.classList.add('d-none');
            }
        }
    }

    if (selectAll) {
        selectAll.addEventListener('change', function() {
            checkboxes.forEach(cb => {
                cb.checked = selectAll.checked;
            });
            updateBulkActionsVisibility();
        });
    }

    checkboxes.forEach(cb => {
        cb.addEventListener('change', function() {
            const allChecked = Array.from(checkboxes).every(c => c.checked);
            selectAll.checked = allChecked;
            updateBulkActionsVisibility();
        });
    });

    const smsModal = document.getElementById('smsModal');
    if (smsModal) {
        smsModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-sms-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
            // Set current browser time
            const clientTimeInput = document.getElementById("client_time");
            if (clientTimeInput) {
                const now = new Date();
                const offset = now.getTimezoneOffset() * 60000;
                const localISOTime = (new Date(now - offset)).toISOString().slice(0, 19);
                clientTimeInput.value = localISOTime;
            }
        });
    }

    const bulkCallModal = document.getElementById('bulkCallModal');
    if (bulkCallModal) {
        bulkCallModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-call-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
        });
    }

    const emailModal = document.getElementById('emailModal');
    if (emailModal) {
        emailModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-email-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
        });
    }

    // Individual Schedule Call Modal dynamic content
    var scheduleCallModal = document.getElementById('scheduleCallModal');
    if (scheduleCallModal) {
        scheduleCallModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var voterId = button.getAttribute('data-voter-id');
            var voterName = button.getAttribute('data-voter-name');
            
            var modalTitle = scheduleCallModal.querySelector('#voterNameLabel');
            var form = scheduleCallModal.querySelector('#scheduleCallForm');
            
            modalTitle.textContent = voterName;
            form.action = '/voters/' + voterId + '/schedule-call/';
        });
    }

    var mapModal = document.getElementById('mapModal');
    if (mapModal) {
        mapModal.addEventListener('shown.bs.modal', function () {
            if (!map) {
                initMap();
            } else {
                google.maps.event.trigger(map, 'resize');
                if (markers.length > 0) {
                    var bounds = new google.maps.LatLngBounds();
                    markers.forEach(function(marker) {
                        bounds.extend(marker.getPosition());
                    });
                    map.fitBounds(bounds);
                }
            }
        });
    }
});
</script>
{% endblock %}