var map, drawnItems, drawControl, googleSat, iconMarker;
var currentMarker = null;

function initMap() {
    map = L.map("map", {
        attributionControl: false,
    }).setView([-8.157416852745705, 113.72281580436439], 16);

    googleSat = L.tileLayer(
        "http://{s}.google.com/vt?lyrs=s&x={x}&y={y}&z={z}",
        {
            maxZoom: 20,
            subdomains: ["mt0", "mt1", "mt2", "mt3"],
        }
    ).addTo(map);

    iconMarker = L.icon({
        iconUrl: "/assets/images/marker.png",
        iconSize: [50, 50],
        iconAnchor: [25, 50],
        popupAnchor: [0, -50],
    });

    currentMarker = L.marker([-8.157416852745705, 113.72281580436439], {
        icon: iconMarker,
        draggable: true,
    })
        .addTo(map)
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan tentukan petak lahan.<br />Pastikan lokasi anda sudah benar.</div>`
        );

    drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    drawControl = new L.Control.Draw({
        draw: {
            polygon: true, // Izinkan user menggambar polygon
            polyline: false,
            rectangle: false,
            circle: false,
            marker: false,
            circlemarker: false,
        },
        edit: {
            featureGroup: drawnItems, // Edit hanya objek yang sudah digambar
            remove: true, // Izinkan menghapus objek
        },
    });
    map.addControl(drawControl);

    map.on("draw:created", handleDrawCreated);
    map.on("draw:edited", handleDrawEdited);

    $("#showModal").on("shown.bs.modal", function () {
        map.invalidateSize();
    });
}

var form = document.getElementById("add-form");
var provinceField = form.querySelector("#province-field");
var provinceVal = new Choices(provinceField);

var regencyContainer = form.querySelector("#regency-container");
var regencyField = form.querySelector("#regency-field");
var regencyVal = new Choices(regencyField, {
    shouldSort: false,
});

var districtContainer = form.querySelector("#district-container");
var districtField = form.querySelector("#district-field");
var districtVal = new Choices(districtField, {
    shouldSort: false,
});

var addressContainer = form.querySelector("#address-container");
var addressField = form.querySelector("#address-field");

var mapContainer = form.querySelector("#map-container");
var latField = form.querySelector("#lat");
var lngField = form.querySelector("#lng");

var polygonField = form.querySelector("#polygon");
var loading = form.querySelector("#loading");

var btnContainer = form.querySelector("#add-footer");

document.addEventListener("DOMContentLoaded", function () {
    initMap();
    if (provinceField.value !== "") {
        getRegencies(provinceField.value);
    }
});

function getRegencies(provinceId) {
    regencyContainer.style.display = "none";
    districtContainer.style.display = "none";
    addressContainer.style.display = "none";
    loading.style.display = "block";
    mapContainer.style.display = "none";

    const url = "/location/get-regency/" + provinceId;
    $.ajax({
        url: url,
        type: "GET",
        success: function (response) {
            if (response.success) {
                loading.style.display = "none";
                const data = response.data;

                regencyVal.clearStore();
                regencyVal.clearChoices();

                regencyVal.value = "";
                regencyVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kabupaten",
                        selected: true,
                        disabled: true,
                    },
                ]);

                if (Array.isArray(data)) {
                    regencyVal.setChoices(
                        data.map((regency) => ({
                            value: regency.id,
                            label: regency.name,
                            selected: false,
                            disabled: false,
                        }))
                    );

                    regencyContainer.style.display = "block";
                } else {
                    mapContainer.style.display = "block";
                    mapContainer.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapContainer.style.display = "block";
            mapContainer.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

function getDistricts(regencyId) {
    districtContainer.style.display = "none";
    addressContainer.style.display = "none";
    loading.style.display = "block";
    mapContainer.style.display = "none";

    const url = "/location/get-district/" + regencyId;
    $.ajax({
        url: url,
        type: "GET",
        success: function (response) {
            if (response.success) {
                loading.style.display = "none";
                const data = response.data;

                districtVal.clearStore();
                districtVal.clearChoices();

                districtVal.value = "";
                districtVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kecamatan",
                        selected: true,
                        disabled: true,
                    },
                ]);

                if (Array.isArray(data)) {
                    districtVal.setChoices(
                        data.map((district) => ({
                            value: district.id,
                            label: district.name,
                            selected: false,
                            disabled: false,
                        }))
                    );

                    districtContainer.style.display = "block";
                } else {
                    mapContainer.style.display = "block";
                    mapContainer.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapContainer.style.display = "block";
            mapContainer.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

function showmap(districtId) {
    loading.style.display = "block";
    if (!navigator.geolocation) {
        alert("Geolocation tidak didukung oleh browser ini.");
        return;
    }

    navigator.geolocation.getCurrentPosition(
        function (position) {
            loading.style.display = "none";

            mapContainer.style.display = "block";
            map.invalidateSize();

            addressContainer.style.display = "block";

            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            map.setView([lat, lng], 16);

            if (currentMarker) {
                map.removeLayer(currentMarker);
            }
            if (currentMarker || currentMarkerEdit) {
                map.removeLayer(currentMarker);
            }

            var iconMarker = L.icon({
                iconUrl: "/assets/images/marker.png",
                iconSize: [50, 50],
                iconAnchor: [25, 50],
                popupAnchor: [0, -50],
            });

            currentMarker = L.marker([lat, lng], {
                icon: iconMarker,
                draggable: true,
            }).addTo(map);

            currentMarker.on("dragend", onPointerDragend);

            currentMarker
                .bindPopup(
                    `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan tentukan petak lahan.<br />Pastikan lokasi anda sudah benar.</div>`
                )
                .openPopup();

            latField.value = lat;
            lngField.value = lng;
        },
        function (error) {
            alert("Error: " + error.message);
        }
    );
}

function onPointerDragend() {
    if (!currentMarker) return;
    var coordinates = currentMarker.getLatLng();

    currentMarker
        .setLatLng(coordinates)
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan tentukan petak lahan.<br />Pastikan lokasi anda sudah benar.</div>`
        )
        .openPopup();

    latField.value = coordinates.lat;
    lngField.value = coordinates.lng;
}

function handleDrawCreated(e) {
    var layer = e.layer;
    drawnItems.addLayer(layer);
    var coordinates = layer.getLatLngs()[0];
    console.log("Koordinat Polygon:", coordinates);
    polygonField.value = JSON.stringify(coordinates);

    layer.bindPopup("<b>Petak Lahan Berhasil Dibuat!</b>").openPopup();
    btnContainer.style.display = "block";
}

function handleDrawEdited(e) {
    var layers = e.layers;
    layers.eachLayer(function (layer) {
        var coordinates = layer.getLatLngs();
        console.log("Koordinat setelah diedit:", coordinates);
        polygonField.value = JSON.stringify(coordinates);

        layer.bindPopup("<b>Petak Lahan Berhasil Diedit!</b>").openPopup();
    });
}
