{% 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">Voter Registry</h1>
        <div class="d-flex gap-2">
            <a href="{% url 'voter_advanced_search' %}" class="btn btn-outline-primary btn-sm">Advanced Search</a>
            {% if can_edit_voter %}
            <a href="/admin/core/voter/add/" class="btn btn-primary btn-sm">+ Add New Voter</a>
            {% endif %}
        </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-10">
                    <input type="text" name="q" class="form-control" placeholder="Search by name or Voter ID..." value="{{ query|default:'' }}">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4">Name</th>
                        <th>District</th>
                        <th>Phone</th>
                        <th>Target Voter</th>
                        <th>Supporter</th>
                        <th class="pe-4 text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for voter in voters %}
                    <tr>
                        <td class="ps-4">
                            <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>
                            {% else %}
                                -
                            {% endif %}
                            {% if voter.secondary_phone %}
                                <div class="d-flex align-items-center small text-muted">
                                    <a href="tel:{{ voter.secondary_phone }}" class="text-decoration-none text-muted 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>
                            {% 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>
                            {% 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 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 me-1"></i>Call Voter
                            </button>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="6" class="text-center py-5 text-muted">
                            <p class="mb-0">No voters found matching your search.</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-item" href="?page=1{% if query %}&q={{ query }}{% endif %}{% for key, value in request.GET.items %}{% if key != 'page' and key != 'q' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="First">
                            <span class="page-link">&laquo;&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ voters.previous_page_number }}{% if query %}&q={{ query }}{% endif %}{% for key, value in request.GET.items %}{% if key != 'page' and key != 'q' %}&{{ 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 }}{% if query %}&q={{ query }}{% endif %}{% for key, value in request.GET.items %}{% if key != 'page' and key != 'q' %}&{{ 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 }}{% if query %}&q={{ query }}{% endif %}{% for key, value in request.GET.items %}{% if key != 'page' and key != 'q' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Last">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
        {% endif %}
    </div>
</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> Voter 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>

<!-- Schedule Call Modal -->
<div class="modal fade" id="scheduleCallModal" tabindex="-1" 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() {
        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);
                    }
                }
            });
        }

        // 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/';
            });
        }
    });
</script>
{% endblock %}