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

{% block content %}
<div class="container-fluid py-4 py-md-5 px-3 px-md-4">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 mb-md-5 gap-3">
        <div>
            <h1 class="h2 fw-bold text-dark mb-1">Yard Sign Requests</h1>
            <p class="text-muted mb-0">View and manage households that have requested a yard sign.</p>
        </div>
        <div class="d-flex flex-column flex-sm-row gap-2">
            <button type="button" class="btn btn-outline-danger shadow-sm py-1 px-4 flex-grow-1" data-bs-toggle="modal" data-bs-target="#mapModal">
                <i class="bi bi-map-fill me-1"></i> View Map
            </button>
        </div>
    </div>

    <!-- Filters Card -->
    <div class="card border-0 shadow-sm rounded-4 mb-4 mb-md-5 overflow-hidden">
        <div class="card-header bg-white py-3 border-0">
            <h5 class="card-title mb-0 fw-bold text-danger">Filters</h5>
        </div>
        <div class="card-body p-3 p-md-4">
            <form method="GET" action="." class="row g-3 align-items-end">
                <div class="col-12 col-md-2">
                    <label class="form-label small fw-bold text-uppercase text-muted">District</label>
                    <input type="text" name="district" class="form-control rounded-3" placeholder="Filter by district..." value="{{ district_filter }}">
                </div>
                <div class="col-12 col-md-2">
                    <label class="form-label small fw-bold text-uppercase text-muted">Neighborhood</label>
                    <input type="text" name="neighborhood" class="form-control rounded-3" placeholder="Filter by neighborhood..." value="{{ neighborhood_filter }}">
                </div>
                <div class="col-12 col-md-2">
                    <label class="form-label small fw-bold text-uppercase text-muted">City</label>
                    <input type="text" name="city" class="form-control rounded-3" placeholder="Filter by city..." value="{{ city_filter }}">
                </div>
                <div class="col-12 col-md-4">
                    <label class="form-label small fw-bold text-uppercase text-muted">Address Search</label>
                    <input type="text" name="address" class="form-control rounded-3" placeholder="Filter by street address..." value="{{ address_filter }}">
                </div>
                <div class="col-12 col-md-2 d-flex gap-2">
                    <button type="submit" class="btn btn-danger w-100 rounded-3">Filter</button>
                    <a href="." class="btn btn-light w-100 rounded-3">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Households List -->
    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-header bg-white py-3 border-bottom d-flex flex-column flex-sm-row justify-content-between align-items-sm-center gap-2">
            <h5 class="card-title mb-0 fw-bold text-dark">Households Wanting Signs</h5>
            <span class="badge bg-danger-subtle text-danger px-3 py-2 rounded-pill w-auto align-self-start align-self-sm-center">
                {{ households.paginator.count }} Households Found
            </span>
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light text-muted">
                    <tr>
                        <th class="ps-4 py-3 text-uppercase small ls-1">Household Address</th>
                        <th class="py-3 text-uppercase small ls-1">Voters Wanting Sign</th>
                        <th class="pe-4 py-3 text-uppercase small ls-1 d-none d-md-table-cell">Neighborhood</th>
                    </tr>
                </thead>
                <tbody>
                    {% for household in households %}
                    <tr>
                        <td class="ps-4">
                            <div class="fw-bold text-dark">{{ household.address_street }}</div>
                            <div class="small text-muted">{{ household.city }}, {{ household.state }} {{ household.zip_code }}</div>
                            <div class="d-md-none mt-1">
                                {% if household.neighborhood %}
                                <span class="badge border border-danger-subtle bg-danger-subtle text-danger fw-medium px-2 py-1 small">
                                    {{ household.neighborhood }}
                                </span>
                                {% endif %}
                            </div>
                        </td>
                        <td>
                            <div class="d-flex flex-wrap gap-1">
                                {% for voter in household.voters_who_want_sign %}
                                <a href="{% url 'voter_detail' voter.id %}" class="badge bg-light text-danger border border-danger-subtle text-decoration-none hover-underline">
                                    {{ voter.first_name }} {{ voter.last_name }}
                                </a>
                                {% endfor %}
                            </div>
                        </td>
                        <td class="pe-4 d-none d-md-table-cell">
                            {% if household.neighborhood %}
                            <span class="badge border border-danger-subtle bg-danger-subtle text-danger fw-medium px-2 py-1">
                                {{ household.neighborhood }}
                            </span>
                            {% else %}
                            <span class="text-muted italic small">Not assigned</span>
                            {% endif %}
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="3" class="text-center py-5">
                            <div class="text-muted mb-2">
                                <i class="bi bi-signpost-2 mb-2" style="font-size: 3rem; opacity: 0.3;"></i>
                            </div>
                            <p class="mb-0 fw-medium">No households wanting signs found.</p>
                            <p class="small text-muted">Try adjusting your filters or search criteria.</p>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        {% if households.paginator.num_pages > 1 %}
        <div class="card-footer bg-white border-0 py-4">
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mb-0">
                    {% if households.has_previous %}
                    <li class="page-item">
                        <a class="page-link rounded-circle mx-1 border-0 bg-light text-dark" href="?page=1{% if district_filter %}&district={{ district_filter|urlencode }}{% endif %}{% if neighborhood_filter %}&neighborhood={{ neighborhood_filter|urlencode }}{% endif %}{% if city_filter %}&city={{ city_filter|urlencode }}{% endif %}{% if address_filter %}&address={{ address_filter|urlencode }}{% endif %}" aria-label="First">
                            <i class="bi bi-chevron-double-left small"></i>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link rounded-circle mx-1 border-0 bg-light text-dark" href="?page={{ households.previous_page_number }}{% if district_filter %}&district={{ district_filter|urlencode }}{% endif %}{% if neighborhood_filter %}&neighborhood={{ neighborhood_filter|urlencode }}{% endif %}{% if city_filter %}&city={{ city_filter|urlencode }}{% endif %}{% if address_filter %}&address={{ address_filter|urlencode }}{% endif %}" aria-label="Previous">
                            <i class="bi bi-chevron-left small"></i>
                        </a>
                    </li>
                    {% endif %}

                    <li class="page-item active mx-1 mx-sm-2"><span class="page-link rounded-pill px-2 px-sm-3 border-0 small">Page {{ households.number }} of {{ households.paginator.num_pages }}</span></li>

                    {% if households.has_next %}
                    <li class="page-item">
                        <a class="page-link rounded-circle mx-1 border-0 bg-light text-dark" href="?page={{ households.next_page_number }}{% if district_filter %}&district={{ district_filter|urlencode }}{% endif %}{% if neighborhood_filter %}&neighborhood={{ neighborhood_filter|urlencode }}{% endif %}{% if city_filter %}&city={{ city_filter|urlencode }}{% endif %}{% if address_filter %}&address={{ address_filter|urlencode }}{% endif %}" aria-label="Next">
                            <i class="bi bi-chevron-right small"></i>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link rounded-circle mx-1 border-0 bg-light text-dark" href="?page={{ households.paginator.num_pages }}{% if district_filter %}&district={{ district_filter|urlencode }}{% endif %}{% if neighborhood_filter %}&neighborhood={{ neighborhood_filter|urlencode }}{% endif %}{% if city_filter %}&city={{ city_filter|urlencode }}{% endif %}{% if address_filter %}&address={{ address_filter|urlencode }}{% endif %}" aria-label="Last">
                            <i class="bi bi-chevron-double-right small"></i>
                        </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-danger 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> Yard Sign Requests 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; position: relative;">
                    <div id="map-controls">
                        <button id="center-user" class="map-control-btn" title="Center on My Location">
                            <i class="bi bi-geo-alt-fill"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 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 userLocationMarker;
    var mapData = {{ map_data_json|safe }};

    function showUserLocation(centerOnUser = false) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                if (userLocationMarker) {
                    userLocationMarker.setPosition(pos);
                } else {
                    userLocationMarker = new google.maps.Marker({
                        position: pos,
                        map: map,
                        title: 'Your Location',
                        icon: {
                            path: google.maps.SymbolPath.CIRCLE,
                            fillColor: '#4285F4',
                            fillOpacity: 1,
                            scale: 8,
                            strokeColor: 'white',
                            strokeWeight: 2
                        }
                    });
                }
                
                if (centerOnUser) {
                    map.setCenter(pos);
                    map.setZoom(15);
                }
            }, function(error) {
                console.warn("Geolocation failed: " + error.message);
            }, {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            });
        }
    }

    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.address,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
                });

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

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

        if (markers.length > 0) {
            map.fitBounds(bounds);
        }
        
        showUserLocation();
        
        var centerBtn = document.getElementById('center-user');
        if (centerBtn) {
            centerBtn.addEventListener('click', function() {
                showUserLocation(true);
            });
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        var mapModalElement = document.getElementById('mapModal');
        if (mapModalElement) {
            mapModalElement.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>

<style>
    .btn-outline-danger {
        color: #dc3545 !important;
        border-color: #dc3545 !important;
    }
    .btn-outline-danger:hover {
        background-color: #dc3545 !important;
        color: #ffffff !important;
    }

    .hover-underline:hover {
        text-decoration: underline !important;
    }
    .bg-danger-subtle {
        background-color: #f8d7da;
    }
    .text-danger {
        color: #dc3545 !important;
    }
    .border-danger-subtle {
        border-color: #f5c2c7 !important;
    }
    .ls-1 {
        letter-spacing: 1px;
    }

    #map-controls {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 5;
    }
    .map-control-btn {
        background-color: #fff;
        border: 2px solid #fff;
        border-radius: 3px;
        box-shadow: 0 2px 6px rgba(0,0,0,.3);
        cursor: pointer;
        margin-bottom: 22px;
        text-align: center;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
    }
</style>
{% endblock %}