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

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

    defineEmits(['reset-vehicle']);

    const initState = {
        truck_type: '',
        categories: '',
        vehicle_number: '',
        city: '',
        state: '',
        trailer_plate_1: '',
        trailer_plate_2: '',
        circulation_serial_number: '',
        notes: '',
        destino: '',
    }

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

    const vehicleForm = reactive({
        ...initState
    })

    const authStore = useAuthStore();
    const vehicleStore = useVehiclesStore();

    onMounted(() => {
        if(props.vehicle) {
            vehicleForm.truck_type = {
                meta_value: props.vehicle.truck_type
            };
            vehicleForm.categories = props.vehicle.categories;
            vehicleForm.vehicle_number = props.vehicle.vehicle_number,
            vehicleForm.city = {city_name: props.vehicle.city},
            vehicleForm.state = {state_name: props.vehicle.state},
            vehicleForm.trailer_plate_1 = props.vehicle.trailer_plate_1;
            vehicleForm.trailer_plate_2 = props.vehicle.trailer_plate_2;
            vehicleForm.circulation_serial_number = props.vehicle.circulation_serial_number;
            vehicleForm.notes = props.vehicle.notes;
            vehicleForm.destino = {city_name: props.vehicle.destino};
        }
    })

    const loading = ref(false);

    const title = computed(() => {
        return (props.vehicle) ? 'Editar vehiculo' : 'Agregar vehiculo';
    });

    const handleSaveVehicle = async() => {
        validations();

        if(errors.value.vehicle_number || errors.value.truck_type || errors.value.categories || errors.value.city || errors.value.state || errors.value.destino ) return;
        let vehicleData ={
	    	vehicle_number : vehicleForm.vehicle_number,
	    	city : vehicleForm.city?.city_name,
	    	state : vehicleForm.state?.state_name,
	    	truck_type : vehicleForm?.truck_type.meta_value,
	    	trailer_plate_1: vehicleForm.trailer_plate_1,
	    	trailer_plate_2: vehicleForm.trailer_plate_2,
	    	circulation_serial_number: vehicleForm.circulation_serial_number,
	    	notes: vehicleForm.notes,
	    	company: authStore.user.company,
	    	categories: vehicleForm.categories.length <= 0 ? null : vehicleForm.categories?.map((e) => e._id),
	    	destino: vehicleForm.destino?.city_name,
	    	available_date: new Date()
	    };
        let localData = {};
        let result = 'error';
        let action = 'Creado';
        loading.value = true;
        if(props.vehicle) {
            localData = {
                categories: vehicleForm.categories,
                driver: props.vehicle.driver
            };
            action = 'actualizado';
            result = await vehicleStore.updateVehicleCompany(props.vehicle._id, vehicleData, localData);
        } else {
            localData = {
                categories: vehicleForm.categories
            }
            action = 'añadido';
            result = await vehicleStore.createVehicleCompany(vehicleData, localData);
        }

        loading.value = false;
        if(result === 'success') {
            document.getElementById('btnClosecreateVehicleModal').click();
            Swal.fire({
                title: `<strong>Vehiculo ${action} con éxito!</strong>`,
                icon: 'success'
            })
        } else {
            Swal.fire({
                title: result,
                icon: 'error'
            })
        }
    }

    const validations = () => {
        errors.value = {
            truck_type: (!vehicleForm.truck_type) ? 'Seleccione tipo de transporte' : null,
            categories: (!vehicleForm.categories) ? 'Seleccione al menos un segmento' : null,
            vehicle_number: (!vehicleForm.vehicle_number) ? 'Campo es requerido' : null,
            state: (!vehicleForm.state) ? 'Seleccione estado' : null,
            city: (!vehicleForm.city) ? 'Seleccione municipio' : null,
            destino: (!vehicleForm.destino) ? 'Seleccione municipio destino' : null,
        };
    }
</script>

<template>
    <div class="modal fade" id="createVehicleModal" tabindex="-1" role="dialog" aria-labelledby="createVehicleModal" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="title mt-2 mb-3">{{ title }}</h2>
                    <button 
                        id="btnClosecreateVehicleModal" 
                        type="button" 
                        @click="$emit('reset-vehicle')"
                        class="close bg-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body form-content">
                    <form @submit.prevent="handleSaveVehicle" autocomplete="off" class="vehicle-form">
                        <div class="row mt-4">
                            <div class="col-lg-6 col-12">
                                <label class="custom-label">Tipo de Transporte*</label>
                                <TruckTypes
                                    v-model="vehicleForm.truck_type" 
                                />
                                <span class="error-msg" v-if="errors.truck_type">{{ errors.truck_type }}</span>
                            </div>
                            <div class="col-lg-6 col-12">
                                <label class="custom-label">Segmento del transporte*</label>
                                <Segments
                                    v-model="vehicleForm.categories" 
                                    :multiple="true"
                                />
                                <span class="error-msg" v-if="errors.categories">{{ errors.categories }}</span>
                            </div>
                        </div>
                        <div class="row mt-4">
                            <div class="col-lg-6 col-12">
                                <CustomInput
                                    label="Número de Serie*"
                                    name="vehicle_number"
                                    v-model:field="vehicleForm.vehicle_number"
                                    :filled="false"
                                    :error="errors.vehicle_number"
                                />
                            </div>
                            <div class="col-lg-6 col-12">
                                <CustomInput
                                    label="Placas Tracto Camión"
                                    name="circulation_serial_number"
                                    v-model:field="vehicleForm.circulation_serial_number"
                                    :filled="false"
                                />
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-6 col-12">
                                <CustomInput
                                    label="Placas Remolque 1"
                                    name="trailer_plate_1"
                                    v-model:field="vehicleForm.trailer_plate_1"
                                    :filled="false"
                                />
                            </div>
                            <div class="col-lg-6 col-12">
                                <CustomInput
                                    label="Placas Remolque 1"
                                    name="trailer_plate_2"
                                    v-model:field="vehicleForm.trailer_plate_2"
                                    :filled="false"
                                />
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-6 col-12">
                                <label class="custom-label">Base de carga por Estado*</label>
                                <States
                                    v-model="vehicleForm.state" 
                                />
                                <span class="error-msg" v-if="errors.state">{{ errors.state }}</span>
                            </div>
                            <div class="col-lg-6 col-12">
                                <label class="custom-label">Base de Carga por Municipio*</label>
                                <Cities
                                    v-model="vehicleForm.city" 
                                />
                                <span class="error-msg" v-if="errors.city">{{ errors.city }}</span>
                            </div>
                        </div>
                        <div class="col-lg-6 col-12 mt-4">
                            <label class="custom-label">Destino*</label>
                            <Cities
                                v-model="vehicleForm.destino" 
                            />
                            <span class="error-msg" v-if="errors.destino">{{ errors.destino }}</span>
                        </div>
                        <div class="d-flex flex-column mt-4">
                            <label class="custom-label" for="notes">Información Adicional del Transporte:</label>
                            <textarea 
                                class="custom-input-light"
                                name="notes" 
                                id="notes" 
                                placeholder="Escribe aqui..."
                                v-model="vehicleForm.notes"
                            ></textarea>
                        </div>
                        <div class="mt-4 text-center">
                            <Spiner v-if="loading"/>
                            <button 
                                v-else
                                class="btn-primary-sm radius-sm" type="submit">Guardar</button>
                        </div> 
                    </form>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
    .vehicle-form {
        padding: 0px 24px;
    }

    @media (max-width: 768px) {
        .vehicle-form {
            padding: 0px 12px;
        }
    }
</style>