<template>
    <Head title="Detalles de la ruta" />

    <AuthenticatedLayout>
        <template #header> Detalles de la ruta </template>

        <div class="p-4">
            <div class="grid gap-4 gap-y-2 text-sm grid-cols-1 lg:grid-cols-2 md:grid-cols-2">
                <div class="rounded-2xl overflow-hidden w-full h-[550px] shadow-md">
                    <MapaRutas ref="mapaRutasRef" :origen="origen" :destino="destino" :apiKey="api_key" :base-url="api_route" />
                </div>
                <div class="bg-white rounded-2xl">
                    <div class="mx-10">
                        <div class="rounded-lg w-full">
                            <ul class="mt-5 relative border-l-2 border-purple-500 pl-4">
                                <li class="mb-6 relative">
                                    <div class="absolute -left-7 w-6 h-6 bg-white border-2 border-purple-600 rounded-full"></div>
                                    <div class="text-sm font-medium text-gray-700 ml-3"><span class="text-purple-600">Origen:</span> {{ formatLocation(ruta.origen) }}</div>
                                </li>
                                <li class="mb-6 relative">
                                    <div class="absolute -left-7 w-6 h-6 bg-white border-2 border-purple-600 rounded-full"></div>
                                    <div class="text-sm font-medium text-gray-700 ml-3"><span class="text-purple-600">Destino:</span> {{ formatLocation(ruta.destino) }}</div>
                                </li>
                                <li class="mb-6 relative">
                                    <div class="absolute -left-7 w-6 h-6 bg-white border-2 border-purple-600 rounded-full"></div>
                                    <div class="text-sm font-medium text-gray-700 ml-3"><span class="text-purple-600">Distancia:</span> {{ ruta.kilometros }} Km</div>
                                </li>
                                <li class="mb-6 relative">
                                    <div class="absolute -left-7 w-6 h-6 bg-white border-2 border-purple-600 rounded-full"></div>
                                    <div class="text-sm font-medium text-gray-700 ml-3"><span class="text-purple-600">Fecha y hora:</span> {{ formatDateTime(ruta.fecha_hora) }}</div>
                                </li>
                                <li class="mb-6 relative">
                                    <div class="absolute -left-7 w-6 h-6 bg-white border-2 border-purple-600 rounded-full"></div>
                                    <div class="text-sm font-medium text-gray-700 ml-3"><span class="text-purple-600">Puestos disponibles:</span> {{ ruta.puestos_disponibles }}</div>
                                </li>
                                
                            </ul>
                        </div>
                        <div class="mt-5">
                            <Button class="w-full" type="button" :disabled="loading" @click="calcularRuta" severity="Primary" outlined>
                                <template #default>
                                    <span v-if="loading" class="cargadorSpan"></span>
                                    {{ loading ? 'Generando...' : 'Ver ruta sugerida' }}
                                </template>
                            </Button>
                        </div>
                        <Message v-if="ruta.indicaciones" class="mt-5" severity="info" icon="pi pi-send">{{ruta.indicaciones}}</Message>
                    </div>
                    <hr class="mt-5 border-gray-300 mx-5" />
                    <div class="mt-5 mx-5">
                        <!-- User -->
                        <button class="w-full text-left focus:outline-none focus-visible:bg-indigo-50">
                            <div class="flex items-center">
                                <img v-if="ruta.conductor.estudiante.foto_perfil" class="rounded-full items-start flex-shrink-0 mr-5 object-cover w-[50px] h-[50px]" :src="url_imagenes+ruta.conductor.estudiante.foto_perfil" />
                                <Avatar v-else :label="ruta.conductor.estudiante?.nombre?.charAt(0).toUpperCase()" class="mr-5" size="large" shape="circle" />
                                <div>
                                    <h4 class="text-sm font-semibold text-gray-800">{{ ruta.conductor.estudiante.nombre }}</h4>
                                    <div class="text-[13px] flex gap-2"><Rating v-model="calificacion" readonly /> ({{calificacion}})</div>
                                    <!-- <a href="tel:3134556733" class="text-blue-600 underline">3134556733</a> -->
                                </div>
                            </div>
                        </button>
                    </div>
                    <hr class="mt-5 border-gray-300 mx-5" />
                    <div class="mt-5 mb-5 mx-5">
                        <button class="w-full text-left focus:outline-none focus-visible:bg-indigo-50">
                            <div class="flex items-center">
                                <div class="rounded-full flex-shrink-0 mr-5 flex justify-center items-center overflow-hidden w-[50px] h-[50px]">
                                    <Image 
                                        :src="url_imagenes+ruta.vehiculo.foto_vehiculo"
                                        alt="Image" 
                                        class="w-full h-full object-cover rounded-full" 
                                        preview 
                                    />
                                </div>
                                
                                <div>
                                    <h4 class="text-sm font-semibold text-gray-800">{{ ruta.vehiculo.marca_vehiculo + ' ' + ruta.vehiculo.linea_vehiculo }}</h4>
                                    <div class="text-[13px] gap-2">{{ ruta.vehiculo.placa }}</div>
                                </div>
                            </div>
                        </button>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-2xl mt-5 lg:px-20 xl:px-20 px-10 py-5">
                <form @submit.prevent="submit">
                    <h4 class="text-lg font-semibold text-gray-800">
                        Solicitar viaje
                    </h4>
                    <div class="grid grid-cols-1 lg:grid-cols-2 md:grid-cols-2 gap-4 mt-2">
                        <div>
                            <InputLabel for="observacion" value="Observaciones" />
                            <Textarea v-model="form.observacion" class="w-full mt-3" rows="4" />
                            <InputError class="mt-2" :message="form.errors.observacion" />
                        </div>
                        <div class="flex items-end justify-end">
                            <Button class="w-full lg:w-36" type="submit" label="Solicitar cupo" severity="primary" />
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <Toast />
        <ConfirmDialog></ConfirmDialog>
    </AuthenticatedLayout>
</template>

<script setup>
import { router } from "@inertiajs/vue3";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
import InputError from "@/Components/InputError.vue";
import InputLabel from "@/Components/InputLabel.vue";
import { Head, useForm } from "@inertiajs/vue3";
import SecondaryButtonReturn from "@/Components/SecondaryButtonReturn.vue";
import MapaRutas from "@/Components/MapaRutas.vue";
import { onMounted, ref } from "vue";
import Button from "primevue/button";
import Image from 'primevue/image';
import Rating from 'primevue/rating';
import Message from 'primevue/message';
import Avatar from 'primevue/avatar';
import Textarea from 'primevue/textarea';

import dayjs from "dayjs";
import "dayjs/locale/es";

import Toast from "primevue/toast";
import ConfirmDialog from 'primevue/confirmdialog';
import { useToast } from "primevue/usetoast";
import { useConfirm } from "primevue/useconfirm";
import { set } from "lodash";
const toast = useToast();

const confirm = useConfirm();

dayjs.locale("es");

const props = defineProps({
    ruta: {
        type: Object,
        default: () => ({}),
    },
    api_key: {
        type: String,
        default: "",
    },
    api_route: {
        type: String,
        default: "",
    },
    url_imagenes: {
        type: String,
        default: "",
    },
});
console.log(props.ruta);

const mapaRutasRef = ref(null);

const calificacion = ref(props.ruta.conductor.puntaje ?? 0);

const origen = {
    lat: props.ruta.lat_origen,
    lon: props.ruta.long_origen,
    name: props.ruta.origen,
};

const destino = {
    lat: props.ruta.lat_destino,
    lon: props.ruta.long_destino,
    name: props.ruta.destino,
};

onMounted(() => {
   
});


const formatLocation = (location) => {
    if (location.includes("Universidad Tecnológica de Pereira")) {
        return "Universidad Tecnológica de Pereira"; // Si la ubicación contiene esta frase, solo retorna eso
    }
    
    // Si no contiene "Universidad Tecnológica de Pereira", tomar los dos primeros elementos del split
    const parts = location.split(',');
    return parts.length > 1 ? parts[0] + ', ' + parts[1] : parts[0];
};

const formatDateTime = (dateTime) => {
    return dayjs(dateTime).format("dddd, D [de] MMMM [de] YYYY h:mm A");
};


const form = useForm({
    id_ruta: props.ruta.id,
    observacion: '',
});


const loading = ref(false);
const loadingSubmit = ref(false);

const calcularRuta = async () => {
    loading.value = true; // Activar el loader

    if (mapaRutasRef.value) {
        await mapaRutasRef.value.calcularRuta();
    }
    setTimeout(() => {
        loading.value = false; // Desactivar el loader
    }, 3000);
};


const submit = () => {
    confirm.require({
        message: '¿Está seguro de solicitar esta ruta? Recuerde que este es un servicio gratuito de viajes compartidos entre miembros de la comunidad universitaria. Ningún conductor debe cobrarle por este trayecto.',
        header: 'Confirmación',
        icon: 'pi pi-exclamation-triangle',
        rejectProps: {
            label: 'Cancelar',
            severity: 'secondary',
            outlined: true
        },
        acceptProps: {
            label: 'Solicitar'
        },
        accept: () => {
            form.post(route("solicitar-viaje.store"), {
                onSuccess: function () {
                    toast.add({
                        severity: "success",
                        summary: "Registro Guardado",
                        detail: "La solicitud se ha enviado exitosamente",
                        life: 5000,
                    });
                    setTimeout(() => {
                        router.visit(route("solicitar-viaje.index"));
                    }, 1000);
                    
                },
            });
        },
        reject: () => {
            toast.add({ severity: 'error', summary: 'Cancelado', detail: 'La acción se ha cancelado', life: 3000 });
        }
    });
};
</script>
<style>
.cargadorSpan {
    width: 20px;
    height: 20px;
    border: 3px solid #6b21a8;
    border-bottom-color: transparent;
    border-radius: 50%;
    display: inline-block;
    box-sizing: border-box;
    animation: rotation 1s linear infinite;
}

@keyframes rotation {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
} 

.p-confirmdialog {
  max-width: 30rem;
}
</style>