{% 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">Door Visits</h1>
            <p class="text-muted mb-0">Manage and track your door-to-door campaign progress.</p>
        </div>
        <div class="d-flex flex-column flex-sm-row gap-2">
            <button type="button" class="btn btn-outline-primary 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>
            <a href="{% url 'neighborhood_counts' %}?city={{ city_filter|urlencode }}&district={{ district_filter|urlencode }}&neighborhood={{ neighborhood_filter|urlencode }}&address={{ address_filter|urlencode }}" class="btn btn-outline-info shadow-sm py-1 px-4 flex-grow-1">
                <i class="bi bi-grid-3x3-gap-fill me-1"></i> Neighborhoods
            </a>
            <a href="{% url 'door_visit_history' %}" class="btn btn-outline-success shadow-sm py-1 px-4 flex-grow-1">
                <i class="bi bi-clock-history me-1"></i> Visit History
            </a>
        </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-primary">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-primary 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">Unvisited Targeted Households</h5>
            <span class="badge bg-primary-subtle text-primary 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">Action</th>
                        <th class="py-3 text-uppercase small ls-1">Household Address</th>
                        <th class="py-3 text-uppercase small ls-1">Targeted Voters</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">
                            <button type="button" class="btn btn-sm btn-primary px-3 shadow-sm py-2" 
                                    data-bs-toggle="modal" data-bs-target="#logVisitModal"
                                    data-address="{{ household.address_street }}"
                                    data-city="{{ household.city }}"
                                    data-state="{{ household.state }}"
                                    data-zip="{{ household.zip_code }}"
                                    data-voters="{{ household.voters_json_str }}">
                                Log Visit
                            </button>
                        </td>
                        <td>
                            <a href="{% url 'log_door_visit' %}?address_street={{ household.address_street|urlencode }}&city={{ household.city|urlencode }}&state={{ household.state|urlencode }}&zip_code={{ household.zip_code|urlencode }}&next_query_string={{ request.GET.urlencode|urlencode }}" class="text-decoration-none">
                                <div class="fw-bold text-dark hover-underline">{{ household.address_street }}</div>
                                <div class="small text-muted">{{ household.city }}</div>
                            </a>
                            <div class="d-md-none mt-1">
                                {% if household.neighborhood %}
                                <span class="badge border border-primary-subtle bg-primary-subtle text-primary 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.target_voters %}
                                <a href="{% url 'voter_detail' voter.id %}" class="badge bg-light text-primary border border-primary-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-primary-subtle bg-primary-subtle text-primary 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="4" class="text-center py-5">
                            <div class="text-muted mb-2">
                                <i class="bi bi-house-dash mb-2" style="font-size: 3rem; opacity: 0.3;"></i>
                            </div>
                            <p class="mb-0 fw-medium">No unvisited households found.</p>
                            <p class="small text-muted">Try adjusting your filters or target more voters.</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-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> Targeted Households 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>

<!-- Log Visit Modal -->
<div class="modal fade" id="logVisitModal" tabindex="-1" aria-labelledby="logVisitModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content rounded-4 border-0 shadow-lg mx-2 mx-md-0">
            <div class="modal-header bg-light border-0 py-3">
                <h5 class="modal-title fw-bold text-dark" id="logVisitModalLabel">Log Door Visit</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{% url 'log_door_visit' %}" method="POST">
                {% csrf_token %}
                <div class="modal-body p-3 p-md-4">
                    <div class="bg-primary-subtle p-3 rounded-3 mb-3 mb-md-4 border border-primary-subtle">
                        <div class="small text-uppercase fw-bold text-primary mb-1">Household Address</div>
                        <div id="modalAddressDisplay" class="h6 h5-md mb-0 fw-bold text-dark"></div>
                    </div>
                    
                    <input type="hidden" name="address_street" id="modal_address_street">
                    <input type="hidden" name="city" id="modal_city">
                    <input type="hidden" name="state" id="modal_state">
                    <input type="hidden" name="zip_code" id="modal_zip_code">
                    <input type="hidden" name="next_query_string" value="{{ request.GET.urlencode }}">

                    <div class="mb-4">
                        <label class="form-label fw-bold text-primary small text-uppercase">Visit Outcome</label>
                        <div class="row g-2">
                            {% for radio in visit_form.outcome %}
                            <div class="col-6 col-md-4">
                                {{ radio.tag }}
                                <label class="btn btn-outline-primary w-100 h-100 d-flex align-items-center justify-content-center text-center py-2 px-2 small" for="{{ radio.id_for_label }}">
                                    {{ radio.choice_label }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="{{ visit_form.notes.id_for_label }}" class="form-label fw-bold text-primary small text-uppercase">Notes / Conversation Summary</label>
                        {{ visit_form.notes }}
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-12 col-md-6">
                            <label class="form-label fw-bold text-primary small text-uppercase">Support Status</label>
                            {{ visit_form.candidate_support }}
                        </div>
                        <div class="col-12 col-md-6 d-flex align-items-end">
                            <div class="form-check mb-2">
                                {{ visit_form.wants_yard_sign }}
                                <label class="form-check-label fw-bold text-dark" for="{{ visit_form.wants_yard_sign.id_for_label }}">
                                    Wants a Yard Sign
                                </label>
                            </div>
                        </div>
                    </div>

                    <hr class="my-4">

                    <div class="bg-light p-3 rounded-3">
                        <div class="form-check mb-3">
                            {{ visit_form.follow_up }}
                            <label class="form-check-label fw-bold text-dark" for="{{ visit_form.follow_up.id_for_label }}">
                                Schedule a Follow-up Call
                            </label>
                        </div>
                        <div id="callNotesContainer" style="display: none;">
                            <div class="mb-3">
                                <label for="{{ visit_form.follow_up_voter.id_for_label }}" class="form-label fw-bold text-primary small text-uppercase">Recipient of the Call</label>
                                {{ visit_form.follow_up_voter }}
                            </div>
                            <div class="mb-3">
                                <label for="{{ visit_form.call_notes.id_for_label }}" class="form-label fw-bold text-primary small text-uppercase">Call Queue Notes</label>
                                {{ visit_form.call_notes }}
                                <div class="form-text small">These notes will be added to the call queue for the default caller.</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light border-0 py-3">
                    <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 shadow-sm">Save Visit</button>
                </div>
            </form>
        </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 if no data
            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
                });

                marker.addListener('click', function() {
                    var logUrl = "{% url 'log_door_visit' %}?address_street=" + encodeURIComponent(item.address_street) + 
                                 "&city=" + encodeURIComponent(item.city) + 
                                 "&state=" + encodeURIComponent(item.state) + 
                                 "&zip_code=" + encodeURIComponent(item.zip_code) + 
                                 "&next_query_string=" + encodeURIComponent("{{ request.GET.urlencode|escapejs }}") + "" + "&source=map";
                    
                    var content = '<strong>' + item.address + '</strong><br>' + 
                                  item.voters + '<br><br>' +
                                  '<a href="' + logUrl + '" class="btn btn-sm btn-primary text-white px-3 py-1">Log Visit</a>';
                                  
                    infowindow.setContent(content);
                    infowindow.open(map, marker);
                });

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

        if (markers.length > 0) {
            map.fitBounds(bounds);
        }
        
        // Initial attempt to show user location
        showUserLocation();
        
        // Setup control button
        var centerBtn = document.getElementById('center-user');
        if (centerBtn) {
            centerBtn.addEventListener('click', function() {
                showUserLocation(true);
            });
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Automatically open map if requested
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('open_map') === '1') {
            var mapModalElement = document.getElementById('mapModal');
            if (mapModalElement) {
                var mapModal = new bootstrap.Modal(mapModalElement);
                mapModal.show();
            }
        }
        
        // Trigger map initialization when modal is shown
        var mapModalElement = document.getElementById('mapModal');
        if (mapModalElement) {
            mapModalElement.addEventListener('shown.bs.modal', function () {
                if (!map) {
                    initMap();
                } else {
                    if (window.google && window.google.maps) {
                        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);
                        }
                    }
                }
            });
        }

        var logVisitModal = document.getElementById('logVisitModal');
        if (logVisitModal) {
            logVisitModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget;
                if (!button) return;
                
                var address = button.getAttribute('data-address');
                var city = button.getAttribute('data-city');
                var state = button.getAttribute('data-state');
                var zip = button.getAttribute('data-zip');

                document.getElementById('modalAddressDisplay').textContent = (address || '') + ', ' + (city || '') + ', ' + (state || '') + ' ' + (zip || '');
                document.getElementById('modal_address_street').value = address || '';
                document.getElementById('modal_city').value = city || '';
                document.getElementById('modal_state').value = state || '';
                document.getElementById('modal_zip_code').value = zip || '';

                // Populate voters dropdown
                var votersJson = button.getAttribute('data-voters');
                if (votersJson) {
                    try {
                        var voters = JSON.parse(votersJson);
                        var voterSelect = document.getElementById('{{ visit_form.follow_up_voter.id_for_label }}');
                        if (voterSelect) {
                            voterSelect.innerHTML = '';
                            voters.forEach(function(voter) {
                                var option = document.createElement('option');
                                option.value = voter.id;
                                option.textContent = voter.name;
                                voterSelect.appendChild(option);
                            });
                        }
                    } catch (e) {
                        console.error("Error parsing voters JSON:", e);
                    }
                }
            });
        }

        // Toggle call notes visibility
        const followUpCheckbox = document.getElementById('{{ visit_form.follow_up.id_for_label }}');
        const callNotesContainer = document.getElementById('callNotesContainer');
        if (followUpCheckbox && callNotesContainer) {
            followUpCheckbox.addEventListener('change', function() {
                callNotesContainer.style.display = this.checked ? 'block' : 'none';
            });
        }
    });
</script>

<style>
    .btn-outline-primary {
        color: #059669 !important;
        border-color: #059669 !important;
    }
    .btn-outline-primary:hover, .btn-check:checked + .btn-outline-primary {
        background-color: #059669 !important;
        color: #ffffff !important;
    }

    .hover-underline:hover {
        text-decoration: underline !important;
    }
    .italic {
        font-style: italic;
    }
    .bg-primary-subtle {
        background-color: #e7f1ff;
    }
    .text-primary {
        color: #0d6efd !important;
    }
    .border-primary-subtle {
        border-color: #9ec5fe !important;
    }
    .last-child-mb-0:last-child {
        margin-bottom: 0 !important;
    }
    .ls-1 {
        letter-spacing: 1px;
    }
    @media (max-width: 767.98px) {
        .h5-md { font-size: 1.25rem; }
        .table-responsive {
            border: 0;
        }
    }

    #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;
    }
    .map-control-btn:hover {
        color: #333;
    }

</style>
{% endblock %}