<script setup>
    import { onMounted, reactive, ref } from 'vue';
    import Spiner from './ui/Spiner.vue';
    import CustomRadioInput from './ui/CustomRadioInput.vue';
    import { useVehiclesStore } from '../stores/vehicles';
    import CustomInput from './ui/CustomInput.vue';
    import States from './ui/States.vue';
    import Cities from './ui/Cities.vue';
    import Swal from 'sweetalert2';

    const props = defineProps({
        vehicle: {
            type: Object
        }
    });

    const statusSelected = ref(null);
    const loading = ref(false);
    const vehicleStore = useVehiclesStore();

    onMounted(() => {   
        statusSelected.value = props.vehicle.is_available === true ? 'Availiable' : 'Booked'
        formAvailiable.state = {state_name: props.vehicle.state};
        formAvailiable.destino = props.vehicle.destino;
        formAvailiable.city = {city_name: props.vehicle.city};
        formAvailiable.available_date = props.vehicle.available_date?.substring(0, 10);
    });

    defineEmits(['reset-vehicle']);

    const formAvailiable = reactive({
        available_date: new Date(),
        destino: '',
        city : '',
	    state : '',
    });

    const errors = ref({
        destino: null,
        city : null,
	    state : null,
    })

    const handleSetStatusVehicle = async() => {
        let vehicleData;
        console.log(statusSelected.value);
        if(statusSelected.value === 'Availiable') {
            console.log('check validations');
            validations();
            if(errors.value.city || errors.value.state || errors.value.destino ) return;
            vehicleData = {
				available_date : formAvailiable.available_date,
                destino: formAvailiable.destino,
                city : formAvailiable.city.city_name,
				state : formAvailiable.state.state_name,
                is_available : true
			}
        } else {
            vehicleData = {
				available_date : null,
                is_available : false
			}
        }
        let localData = {
            driver: props.vehicle.driver,
            categories: props.vehicle.categories
        }
        loading.value = true;
        const result = await vehicleStore.updateVehicleCompany(props.vehicle._id, vehicleData, localData);
        loading.value = false;
        if(result === 'success') {
            document.getElementById('btnCloseeditStatusVehicle').click();
            Swal.fire({
                title: `<strong>Status del vehiculo actualizado con éxito!</strong>`,
                icon: 'success'
            })
        } else {
            Swal.fire({
                title: result,
                icon: 'error'
            })
        }
    }

    const validations = () => {
        errors.value = {
            state: (!formAvailiable.state) ? 'Seleccione estado' : null,
            city: (!formAvailiable.city) ? 'Seleccione municipio' : null,
            destino: (!formAvailiable.destino) ? 'Ingrese destino' : null,
        };
    }

</script>

<template>
    <div class="modal fade" id="editStatusVehicle" tabindex="-1" role="dialog" aria-labelledby="editStatusVehicle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="title mt-2 mb-3">Cambiar status vehiculo</h2>
                    <button 
                        id="btnCloseeditStatusVehicle" 
                        type="button" 
                        class="close bg-white" 
                        data-dismiss="modal" 
                        @click="$emit('reset-vehicle')"
                        aria-label="Close"
                    >
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body view-proposals">
                    <form @submit.prevent="handleSetStatusVehicle">
                        <div class="custom-selected-field">
                            <h4 class="custom-label my-3">Status del vehiculo</h4>
                            <div class="d-flex">
                                <CustomRadioInput
                                    value="Booked" 
                                    label="Reservado"
                                    :name="'status-vehicle' + vehicle._id"
                                    v-model:typeselected="statusSelected"
                                />
                                <CustomRadioInput
                                    value="Availiable" 
                                    label="Disponible"
                                    :name="'status-vehicle' + vehicle._id"
                                    v-model:typeselected="statusSelected"
                                />
                            </div>
                        </div>
                        <div v-if="statusSelected === 'Availiable'">
                            <CustomInput
                                label="Fecha de carga*"
                                type="date"
                                :filled="false"
                                name="date-load"
                                v-model:field="formAvailiable.available_date"
                            />
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Base de carga por Estado</label>
                                <States
                                    v-model="formAvailiable.state" 
                                />
                                <span class="error-msg" v-if="errors.state">{{ errors.state }}</span>
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Base de Carga por Municipio</label>
                                <Cities
                                    v-model="formAvailiable.city" 
                                />
                                <span class="error-msg" v-if="errors.city">{{ errors.city }}</span>
                            </div>
                            <CustomInput
                                label="Destino*"
                                type="text"
                                :filled="false"
                                name="destino"
                                v-model:field="formAvailiable.destino"
                                :error="errors.destino"
                            />
                        </div>
                        <div class="mt-4 text-center">
                            <Spiner v-if="loading === true"/>
                            <button 
                                v-else
                                class="btn-primary-sm radius-sm"
                                type="submit"
                            >
                                <span class="clear-xsm">Cuardar</span>
                            </button>
                        </div>
                    </form>
                </div>
                <!-- <div class="modal-footer">
                    <button 
                        type="button" 
                        class="btn btn-dark radius-sm" 
                        data-dismiss="modal"
                        @click="$emit('reset-vehicle')"
                    >Cerrar</button>
                </div> -->
            </div>
        </div>
    </div>
</template>

<style scoped>

</style>