console.log("Index Script Loaded Started")
$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize Google Maps
    initMap();

    // Event handler for Save Address button
    document.getElementById('saveAddress').addEventListener('click', function() {
        document.getElementById('addressName').value = '';
        document.getElementById('modalLatitude').value = document.getElementById('latitude').value;
        document.getElementById('modalLongitude').value = document.getElementById('longitude').value;
        document.getElementById('addressId').value = ''; // Clear hidden ID field

        document.getElementById('saveAddressModalButton').style.display = 'block';
        document.getElementById('updateAddressModalButton').style.display = 'none';

        $('#addressModal').modal('show');
    });

    // Event handler for Update Address button
    document.getElementById('updateAddress').addEventListener('click', function() {
        const selectedOption = document.getElementById('addressDropdown').options[document.getElementById('addressDropdown').selectedIndex];
        const addressId = selectedOption.value;
        const addressName = selectedOption.dataset.add;
        const latitude = parseFloat(document.getElementById('latitude').value);
        const longitude = parseFloat(document.getElementById('longitude').value);

        if (addressId) {
            document.getElementById('addressName').value = addressName;
            document.getElementById('modalLatitude').value = latitude;
            document.getElementById('modalLongitude').value = longitude;
            document.getElementById('addressId').value = addressId;

            document.getElementById('saveAddressModalButton').style.display = 'none';
            document.getElementById('updateAddressModalButton').style.display = 'block';

            $('#addressModal').modal('show');
        } else {
            alert('Please select an address from the dropdown.');
        }
    });

    // Event handler for Save Address button in the modal
    document.getElementById('saveAddressModalButton').addEventListener('click', function() {
        const addressName = document.getElementById('addressName').value;
        const latitude = document.getElementById('modalLatitude').value;
        const longitude = document.getElementById('modalLongitude').value;

        if (addressName && latitude && longitude) {
            $.ajax({
                url: '/save_address',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    address_name: addressName,
                    latitude: latitude,
                    longitude: longitude
                }),
                success: function(response) {
                    alert(response.message);
                    $('#addressModal').modal('hide');
                    location.reload();
                },
                error: function(error) {
                    alert('Error saving address');
                    console.error(error);
                }
            });
        } else {
            alert('Please enter all required fields.');
        }
    });

    // Event handler for Update Address button in the modal
    document.getElementById('updateAddressModalButton').addEventListener('click', function() {
        const addressId = document.getElementById('addressId').value;
        const addressName = document.getElementById('addressName').value;
        const latitude = document.getElementById('modalLatitude').value;
        const longitude = document.getElementById('modalLongitude').value;

        if (addressId && addressName && latitude && longitude) {
            $.ajax({
                url: '/update_address',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: addressId,
                    address_name: addressName,
                    latitude: latitude,
                    longitude: longitude
                }),
                success: function(response) {
                    alert(response.message);
                    $('#addressModal').modal('hide');
                    location.reload();
                },
                error: function(error) {
                    alert('Error updating address');
                    console.error(error);
                }
            });
        } else {
            alert('Please enter all required fields.');
        }
    });

    // Handle dropdown selection
    $(document).ready(function() {
        $('#addressDropdown').select2({
            placeholder: 'Select Address',
            allowClear: true
        });
        $('#addressDropdown').on('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const address = selectedOption.dataset.add;
            const latitude = parseFloat(selectedOption.dataset.lat);
            const longitude = parseFloat(selectedOption.dataset.lng);

            if (this.selectedIndex === 0) { // Default "Select Address" value
                document.getElementById('mapLookupInput').disabled = false;
                document.getElementById('saveAddress').style.display = 'block';
                document.getElementById('updateAddress').style.display = 'none';
                document.getElementById('latitude').value = '';
                document.getElementById('longitude').value = '';
            } else {
                document.getElementById('mapLookupInput').disabled = true;
                document.getElementById('saveAddress').style.display = 'none';
                document.getElementById('updateAddress').style.display = 'block';

                // Populate the form fields with the selected address details
                document.getElementById('latitude').value = latitude;
                document.getElementById('longitude').value = longitude;

                const location = new google.maps.LatLng(latitude, longitude);
                placeMarker(location);

                document.getElementById('addressName').value = address;
                document.getElementById('modalLatitude').value = latitude;
                document.getElementById('modalLongitude').value = longitude;
                document.getElementById('addressId').value = selectedOption.value;
            }
        });
    });

    // Handle map click
    google.maps.event.addListener(map, 'click', function(event) {
        if (document.getElementById('addressDropdown').selectedIndex === 0) { // Default "Select Address" value
            placeMarker(event.latLng);
            document.getElementById('latitude').value = event.latLng.lat();
            document.getElementById('longitude').value = event.latLng.lng();
        } else { // When an address is selected from dropdown
            placeMarker(event.latLng);
            document.getElementById('latitude').value = event.latLng.lat();
            document.getElementById('longitude').value = event.latLng.lng();
            document.getElementById('updateAddress').style.display = 'block';
            document.getElementById('saveAddress').style.display = 'none';
        }
    });

    // Handle marker drag
    google.maps.event.addListener(marker, 'dragend', function(event) {
        if (document.getElementById('addressDropdown').selectedIndex === 0) { // Default "Select Address" value
            document.getElementById('latitude').value = event.latLng.lat();
            document.getElementById('longitude').value = event.latLng.lng();
        } else { // When an address is selected from dropdown
            document.getElementById('latitude').value = event.latLng.lat();
            document.getElementById('longitude').value = event.latLng.lng();
            document.getElementById('updateAddress').style.display = 'block';
            document.getElementById('saveAddress').style.display = 'none';
        }
    });

    // Initialize Google Maps
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 38.9071, lng: -77.0368 },
            zoom: 8
        });

        marker = new google.maps.Marker({
            position: map.getCenter(),
            map: map,
            draggable: true
        });

        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
            if (document.getElementById('addressDropdown').selectedIndex === 0) {
                handleMapSelection();
            }
        });

        google.maps.event.addListener(marker, 'dragend', function(event) {
            if (document.getElementById('addressDropdown').selectedIndex === 0) {
                document.getElementById('latitude').value = event.latLng.lat();
                document.getElementById('longitude').value = event.latLng.lng();
                document.getElementById('saveAddress').style.display = 'block';
                document.getElementById('updateAddress').style.display = 'none';
            } else {
                document.getElementById('latitude').value = event.latLng.lat();
                document.getElementById('longitude').value = event.latLng.lng();
                document.getElementById('updateAddress').style.display = 'block';
                document.getElementById('saveAddress').style.display = 'none';
            }
        });

        placeMarker(map.getCenter());
    }

    // Place a marker on the map
    function placeMarker(location) {
        marker.setPosition(location);
        map.panTo(location);
        document.getElementById('latitude').value = location.lat();
        document.getElementById('longitude').value = location.lng();
    }

    // Perform map lookup based on address input
    function performMapLookup() {
        const address = document.getElementById('mapLookupInput').value;
        if (address) {
            const geocoder = new google.maps.Geocoder();
            geocoder.geocode({ address: address }, function(results, status) {
                if (status === 'OK') {
                    map.setCenter(results[0].geometry.location);
                    placeMarker(results[0].geometry.location);
                    handleMapSelection(); // Call to update button visibility and input state
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
        }
    }

    // Handle Enter key for map lookup
    document.getElementById('mapLookupInput').addEventListener('keypress', function(event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            performMapLookup();
        }
    });

    document.getElementById('lookupIcon').addEventListener('click', performMapLookup);

    document.getElementById('mapForm').addEventListener('submit', function(event) {
        event.preventDefault();
        performMapLookup();
    });

    // TODO Populate Data button click event
    document.getElementById('populateButton').addEventListener('click', function() {
        const latitude = document.getElementById('latitude').value;
        const longitude = document.getElementById('longitude').value;

        const fromInput = document.getElementById('fromInput').value;
        const toInput = document.getElementById('toInput').value;

        const searchInput = Array.from(document.querySelectorAll('input.form-check-input:checked')).map(checkbox => checkbox.value);
        console.log(searchInput)

        // Clear previous highlights
        document.querySelectorAll('.form-control, .form-check-input').forEach(el => {
            el.classList.remove('border-red');
            el.classList.remove('focus');
        });

        let hasError = false;

        if (searchInput.length === 0) {
            // Highlight all checkboxes and focus on the first one
            const checkboxes = document.querySelectorAll('input.form-check-input');
            checkboxes.forEach(el => {
                el.classList.add('border-red-checkbox');
            });
            if (checkboxes.length > 0) {
                checkboxes[0].focus(); // Focus on the first checkbox
            }
            hasError = true;
        }


        if (!latitude) {
            document.getElementById('latitude').classList.add('border-red');
            document.getElementById('latitude').focus();
            hasError = true;
        }

        if (!longitude) {
            document.getElementById('longitude').classList.add('border-red');
            document.getElementById('longitude').focus();
            hasError = true;
        }


        if (hasError) {
            alert('Please fill in all fields.');
            return;
        }

        document.getElementById('overlay').style.display = 'block';
        document.getElementById('loader').style.display = 'block';

        $.ajax({
            url: '/populate_data',
            type: 'POST',
            contentType: 'application/json',
            timeout: 600000, 
            data: JSON.stringify({
                latitude: latitude,
                longitude: longitude,
                fromInput:fromInput,
                toInput:toInput,
                searchInput: searchInput
            }),
            success: function(response) {
                document.getElementById('overlay').style.display = 'none';
                document.getElementById('loader').style.display = 'none';
                displayResults(response);
                scrollToResults();
            },
            error: function(error) {
                document.getElementById('overlay').style.display = 'none';
                document.getElementById('loader').style.display = 'none';
                alert('Error populating data');
                console.error(error);
            }
        });
    });

    // Remove the red border from all checkboxes when any checkbox is clicked
    document.querySelectorAll('input.form-check-input').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            // Remove red border from all checkboxes
            document.querySelectorAll('input.form-check-input').forEach(el => {
                el.classList.remove('border-red-checkbox');
            });
        });
    });



    // Clear Button click event
    document.getElementById('clearButton').addEventListener('click', function() {
        document.getElementById('mapLookupInput').value = '';
        document.getElementById('latitude').value = '';
        document.getElementById('longitude').value = '';
        //document.getElementById('milesInput').value = '';

        document.getElementById('dataDisplay').style.display = 'none';
        document.getElementById('overlay').style.display = 'none';
        document.getElementById('loader').style.display = 'none';

        const mapCenter = new google.maps.LatLng(38.9071, -77.0368);
        map.setCenter(mapCenter);
        placeMarker(mapCenter);
    });

    // Handle map selection or manual input
    function handleMapSelection() {
        document.getElementById('mapLookupInput').disabled = false;
        document.getElementById('saveAddress').style.display = 'block';
        document.getElementById('updateAddress').style.display = 'none';
    }
});

function scrollToResults() {
    const resultsSection = document.getElementById('dataDisplay');
    resultsSection.scrollIntoView({ behavior: 'smooth' });
}

console.log("Index Script Loaded Successfully")