var mapEdit, drawnItems, drawControl, googleSat, iconMarker;
var currentMarkerEdit = null;

var formEdit = document.getElementById("edit-form");
var provinceEditField = formEdit.querySelector("#province-edit-field");
var provinceEditVal = new Choices(provinceEditField);

var regencyEditContainer = formEdit.querySelector("#regency-edit-container");
let regencyCode = formEdit.querySelector("#regency-code").dataset.regency;
var regencyEditField = formEdit.querySelector("#regency-edit-field");
var regencyEditVal = new Choices(regencyEditField, {
    shouldSort: false,
});

var districtEditContainer = formEdit.querySelector("#district-edit-container");
let districtCode = formEdit.querySelector("#district-code").dataset.district;
var districtEditField = formEdit.querySelector("#district-edit-field");
var districtEditVal = new Choices(districtEditField, {
    shouldSort: false,
});

var addressEditContainer = formEdit.querySelector("#address-edit-container");
var addressEditField = formEdit.querySelector("#address-edit-field");

var mapEditConatiner = formEdit.querySelector("#map-edit-container");
var latEditField = formEdit.querySelector("#lat-edit");
var lngEditField = formEdit.querySelector("#lng-edit");
var polygonField = formEdit.querySelector("#polygon-edit");

let latDb = formEdit.querySelector("#lat-db").dataset.lat;
let lngDb = formEdit.querySelector("#lng-db").dataset.lng;
let polygonDb = formEdit.querySelector("#polygon-db");
let polygonData = polygonDb.getAttribute("data-polygon");

var loadingEdit = formEdit.querySelector("#loading-edit");
var btnEditContainer = formEdit.querySelector("#edit-footer");

function initMapEdit() {
    mapEdit = L.map("map-edit", {
        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(mapEdit);

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

    currentMarkerEdit = L.marker([-8.157416852745705, 113.72281580436439], {
        icon: iconMarker,
        draggable: true,
    })
        .addTo(mapEdit)
        .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();
    mapEdit.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
        },
    });
    mapEdit.addControl(drawControl);

    mapEdit.on("draw:created", handleDrawCreated);
    mapEdit.on("draw:edited", handleDrawEdited);
    mapEdit.on("draw:deleted", handleDrawDeleted);
    mapEdit.invalidateSize();
}

document.addEventListener("DOMContentLoaded", function () {
    initMapEdit();
    getRegencies(provinceEditField.value);
    getDistricts(regencyCode);
    setMapEdit();
});

function getProvinces(provinceId) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "/location/get-province",
            type: "GET",
            success: function (response) {
                if (response.success) {
                    const province = response.data.find(
                        (province) => province.id == provinceId
                    );

                    resolve(province);
                } else {
                    reject(new Error("Terjadi kesalahan saat mengambil data"));
                }
            },
            error: function (xhr, status, error) {
                reject(new Error("Terjadi kesalahan saat mengambil data"));
            },
        });
    });
}

function getRegencies(provinceId) {
    regencyEditContainer.style.display = "none";
    districtEditContainer.style.display = "none";
    addressEditContainer.style.display = "none";
    loadingEdit.style.display = "block";
    mapEditConatiner.style.display = "none";

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

                regencyEditVal.clearStore();
                regencyEditVal.clearChoices();

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

                if (Array.isArray(data)) {
                    regencyEditVal.setChoices(
                        data.map((regency) => ({
                            value: regency.id,
                            label: regency.name,
                            selected: regency.id == regencyCode,
                            disabled: false,
                        }))
                    );
                    regencyEditContainer.style.display = "block";
                } else {
                    mapEditConatiner.style.display = "block";
                    mapEditConatiner.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapEditConatiner.style.display = "block";
            mapEditConatiner.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

function getDistricts(regencyId) {
    districtEditContainer.style.display = "none";
    addressEditContainer.style.display = "none";
    loadingEdit.style.display = "block";
    mapEditConatiner.style.display = "none";
    handleDrawDeleted();

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

                districtEditVal.clearStore();
                districtEditVal.clearChoices();

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

                if (Array.isArray(data)) {
                    districtEditVal.setChoices(
                        data.map((district) => ({
                            value: district.id,
                            label: district.name,
                            selected: district.id == districtCode,
                            disabled: false,
                        }))
                    );
                    districtEditContainer.style.display = "block";
                } else {
                    mapEditConatiner.style.display = "block";
                    mapEditConatiner.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapEditConatiner.style.display = "block";
            mapEditConatiner.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

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

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

            mapEditConatiner.style.display = "block";
            mapEdit.invalidateSize();

            addressEditContainer.style.display = "block";

            btnEditContainer.style.display = "block";

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

            console.log(lat, lng);

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

            if (currentMarkerEdit) {
                mapEdit.removeLayer(currentMarkerEdit);
            }

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

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

            currentMarkerEdit.on("dragend", onPointerDragend);

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

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

function setMapEdit() {
    loadingEdit.style.display = "block";

    mapEditConatiner.style.display = "block";
    mapEdit.invalidateSize();
    addressEditContainer.style.display = "block";
    btnEditContainer.style.display = "block";
    mapEdit.setView([latDb, lngDb], 16);

    if (polygonData) {
        let coordinates = JSON.parse(polygonData);
        console.log("Polygon Data:", coordinates);

        let latlngs = coordinates.map((point) => [point.lat, point.lng]);
        let polygon = L.polygon(latlngs, { color: "blue" }).addTo(mapEdit);
        drawnItems.addLayer(polygon);
        mapEdit.fitBounds(polygon.getBounds());
        polygonField.value = JSON.stringify(coordinates);
    }

    if (currentMarkerEdit) {
        mapEdit.removeLayer(currentMarkerEdit);
    }

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

    currentMarkerEdit = L.marker([latDb, lngDb], {
        icon: iconMarker,
        draggable: true,
    }).addTo(mapEdit);

    currentMarkerEdit.on("dragend", onPointerDragend);

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

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();
    btnEditContainer.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();
    });
}

function handleDrawDeleted(e) {
    drawnItems.clearLayers();
    polygonField.value = "";
}

function onPointerDragend() {
    if (!currentMarkerEdit) return;
    var coordinates = currentMarkerEdit.getLatLng();
    currentMarkerEdit
        .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();

    latEditField.value = coordinates.lat;
    lngEditField.value = coordinates.lng;
}
