<template>
    <div class="relative w-full">
        <IconField>
            <InputIcon class="pi pi-map-marker" style="color: #9333ea;" />
            <InputText 
                v-model="query" 
                :disabled="disabled"
                @input="handleInput" 
                placeholder="Buscar ubicación..." 
                class="border p-2 rounded w-full mt-1" 
            />
        </IconField>
        <ul 
            v-if="locations.length" 
            class="absolute top-full left-0 w-full bg-white border rounded shadow max-h-52 overflow-y-auto z-50"
        >
            <li
                v-for="location in locations"
                :key="location.place_id"
                @click="selectLocation(location)"
                class="p-2 cursor-pointer hover:bg-gray-200"
            >
                {{ location.display_name }}
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch, onMounted } from "vue";
import axios from "axios";
import { debounce } from "lodash";
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import InputText from 'primevue/inputtext';

const props = defineProps({
    defaultLocation: Object,
    disabled: Boolean,
});

const query = ref("");
const locations = ref([]);
const emit = defineEmits(["locationSelected"]);

// Coordenadas aproximadas del departamento de Risaralda, Colombia
const RISARALDA_BBOX = "-76.24,4.28,-75.33,5.45"; // [min_lon, min_lat, max_lon, max_lat]

const searchLocation = async () => {
    if (query.value.length < 3) {
        locations.value = [];
        return;
    }

    try {
        const { data } = await axios.get(
            `https://nominatim.openstreetmap.org/search?format=json&q=${query.value}&countrycodes=CO&addressdetails=1&viewbox=${RISARALDA_BBOX}&bounded=1`
        );

        // Filtramos solo resultados que tengan una dirección válida en Risaralda, Colombia
        locations.value = data.filter(location =>
            location.address && location.address.state === "Risaralda"
        );

    } catch (error) {
        console.error("Error al buscar ubicaciones:", error);
    }
};

const handleInput = debounce(searchLocation, 500);


const cleanLocationName = (name) => {
    if (name.includes("Plazoleta de banderas, Universidad, AMCO")) {
        return "Universidad Tecnológica de Pereira, Conexión vial Álamos – Pinares, Los Alamos, Universidad, Perímetro Urbano Pereira, Pereira, Risaralda, RAP Eje Cafetero, 660003, Colombia";
    }
    return name;
};

const selectLocation = (location) => {
    if (!location.display_name) {
        return; // Evita seleccionar ubicaciones sin nombre
    }

    const fixedName = cleanLocationName(location.display_name);

    query.value = location.display_name;
    locations.value = [];

    emit("locationSelected", {
        lat: location.lat,
        lon: location.lon,
        name: fixedName
    });
};

// Verificar si `defaultLocation` está definida y actualizar `query`
onMounted(async () => {
    if (props.defaultLocation && props.defaultLocation.lat && props.defaultLocation.lon) {
        try {
            const { data } = await axios.get(
                `https://nominatim.openstreetmap.org/reverse?format=json&lat=${props.defaultLocation.lat}&lon=${props.defaultLocation.lon}&countrycodes=CO`
            );

            if (data.display_name) {
                const fixedName = cleanLocationName(data.display_name);
                query.value = fixedName;
                emit("locationSelected", {
                    lat: props.defaultLocation.lat,
                    lon: props.defaultLocation.lon,
                    name: fixedName
                });
            }
        } catch (error) {
            console.error("Error obteniendo el nombre de la ubicación:", error);
        }
    }
});

watch(() => props.defaultLocation, async (newLocation) => {
    if (newLocation && newLocation.lat && newLocation.lon) {
        try {
            const { data } = await axios.get(
                `https://nominatim.openstreetmap.org/reverse?format=json&lat=${newLocation.lat}&lon=${newLocation.lon}&countrycodes=CO`
            );

            if (data.display_name) {
                const fixedName = cleanLocationName(data.display_name);
                query.value = fixedName;
                emit("locationSelected", {
                    lat: newLocation.lat,
                    lon: newLocation.lon,
                    name: fixedName
                });
            }
        } catch (error) {
            console.error("Error obteniendo el nombre de la ubicación:", error);
        }
    } else {
        query.value = "";
    }
});


</script>

<style>
ul {
    min-width: 100%;
}
</style>
