<template>
    <div class="relative w-full h-full map">
        <div class="absolute top-0 right-0 z-10 w-full p-3">
            <GmapAutocomplete
                :placeholder="placeholder"
                @place_changed="setPlace"
                :select-first-on-enter="true"
            />
        </div>
        <!-- @click="updateCenter" -->
        <!-- maxZoom: 18,
        minZoom: 12, -->
        <GmapMap
            ref="map"
            :center="mapCenter"
            :options="{
                mapTypeControl: false,
                scaleControl: false,
                rotateControl: false,
                fullscreenControl: false,
                disableDefaultUI: true,
            }"
            :zoom="15"
            class="h-full overflow-hidden rounded-lg"
            style="width: 100%; height: 100%"
            @drag="updateCoordinates($event)"
            @dragend="updateCoordinates($event)"
        >
            <!-- <GmapMarker
                :position="{
                    lat: _center.lat,
                    lng: _center.lng,
                }"
                :clickable="true"
            ></GmapMarker> -->
            <!-- :icon="'/assets/Dot.svg'" -->

            <GmapMarker
                v-for="marker in items"
                :key="marker.id"
                :position="{
                    lat: marker.location.lat,
                    lng: marker.location.long,
                }"
                :clickable="true"
                :icon="'/assets/Dot.svg'"
                @mouseover="openMarker(marker.id)"
                @mouseleave="openMarker('onleave')"
            >
                <!-- @closeclick="openMarker(null)" -->
                <GMapInfoWindow
                    @mouseleave="openMarker(null)"
                    :opened="openedMarkerID === marker.id"
                >
                    <Serves_map
                        v-if="type === 'service'"
                        :service="marker"
                        :key="marker.id"
                    />
                    <Project_map
                        v-if="type === 'project'"
                        :project="marker"
                        :key="marker.id"
                    />
                </GMapInfoWindow>
            </GmapMarker>
        </GmapMap>

        <!-- @click="geolocation" -->
        <button
            class="absolute bottom-0 right-0 p-2 -translate-x-2 border-[#2F2F3550] -translate-y-5 bg-white border rounded-md shadow"
            @click="getCurrentLocation"
        >
            <svg
                class="icon icon-tabler icon-tabler-current-location"
                fill="none"
                height="20"
                stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="1.5"
                viewBox="0 0 24 24"
                width="20"
                xmlns="http://www.w3.org/2000/svg"
            >
                <path d="M0 0h24v24H0z" fill="none" stroke="none" />
                <circle cx="12" cy="12" r="3" />
                <circle cx="12" cy="12" r="8" />
                <line x1="12" x2="12" y1="2" y2="4" />
                <line x1="12" x2="12" y1="20" y2="22" />
                <line x1="20" x2="22" y1="12" y2="12" />
                <line x1="2" x2="4" y1="12" y2="12" />
            </svg>
        </button>
    </div>
</template>

<script>
import {
    Autocomplete as GmapAutocomplete,
    Map as GmapMap,
    Marker as GmapMarker,
} from "@fawmi/vue-google-maps";
import { getDistance } from "@/composables/location";
import { debounce } from "@/helpers/general";
import Serves_map from "@/components/Filtration/Serves_map.vue";
// import Popper from "vue3-popper";
import Project_map from "@/components/Filtration/Project_map.vue";
export default {
    props: {
        placeholder: {
            type: String,
            default: "Search for a place",
        },
        radius: {
            type: Number,
            default: 1,
        },
        center: {
            type: Object,
            default: null,
        },
        items: {
            type: Array,
            default: [],
        },
        type: {
            type: String,
            default: "service",
        },
    },
    data() {
        return {
            mapCenter: {
                latitude: 0,
                longitude: 0,
            },
            _center: {
                lat: 0,
                lng: 0,
            },
            _radius: 0,
            bounds: null,
            openedMarkerID: null,
            initial: true,
        };
    },
    methods: {
        async geolocation() {
            navigator.geolocation.getCurrentPosition((position) => {
                // removed auto detection by client request
                // if (this.center) this._center = this.center;
                // else
                this._center = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                };
                this.mapCenter = this._center;
                // this.getPlace();
            });
        },
        async setPlace(place) {
            if (place.geometry?.location) {
                this._center = {
                    lat: place.geometry.location.lat(),
                    lng: place.geometry.location.lng(),
                };
                this.mapCenter = this._center;
            }
        },
        async updateCenter(place) {
            this._center.lat = place.latLng.lat();
            this._center.lng = place.latLng.lng();
        },
        async initMap() {
            this.getCurrentLocation();
        },
        async getCurrentLocation() {
            const vm = this;
            // if (this.$refs.map)
            this.$refs?.map?.$mapPromise?.then(async (map) => {
                vm.detectZoomChange();
                vm.detectBoundChange();
                vm.geolocation();
            });
        },
        async getPlace() {
            const place = await this.$refs.autocomplete.getPlace();
        },
        updateCoordinates() {
            const center = this.$refs.map.$mapObject.center;
            this._center = {
                lat: center.lat(),
                lng: center.lng(),
            };
        },
        detectZoomChange() {
            const vm = this;
            this.$refs.map.$mapObject.addListener("zoom_changed", () => {
                // console.log(this.$refs.map.getZoom());
                this.updateCoordinates();
            });
        },
        detectBoundChange() {
            const vm = this;
            const map = this.$refs.map.$mapObject;
            google.maps.event.addListener(map, "bounds_changed", () => {
                vm.bounds = map.getBounds();
                vm._radius = vm.getRadius();
            });
        },

        // method to get the viewable radius of the map in vuejs
        getRadius() {
            const ne = this.bounds.getNorthEast();
            const right = new google.maps.LatLng(this._center.lat, ne.lng());
            return getDistance(this._center, right);
        },
        openMarker(id) {
            this.openedMarkerID = id;
        },
    },
    watch: {
        _center: {
            handler: debounce(function (val) {
                this.$emit("update:center", val);
            }, 25),
            deep: true,
        },
        _radius: {
            handler: debounce(function (val) {
                this.$emit("update:radius", val);
            }, 25),
            deep: true,
        },
    },

    mounted() {
        this.initMap();
    },
    components: {
        GmapMap,
        GmapMarker,
        GmapAutocomplete,
        Serves_map,
        Project_map,
    },
};
</script>

<style>
.vue-map .gm-ui-hover-effect {
    top: 0px !important;
    right: 0px !important;
    display: none !important;
}
</style>
