<script setup>
    import { computed, onMounted, reactive, ref } from 'vue';
    import CustomInput from './ui/CustomInput.vue';
    import TruckTypes from './ui/TruckTypes.vue';
    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 { validateEmail } from '../helpers/validations';

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

    onMounted(() => {
        if(props.user) {
            console.log(props.user)
            userForm.name = props.user.first_name;
            userForm.last_name = props.user.last_name;
            userForm.email = props.user.email;
            userForm.phone = props.user.phone;
            userForm.phone2 = props.user.phone2;
            userForm.job_role = props.user.job_role;
            userForm.categories = props.user.categories;
            userForm.user_city = props.user.user_city.map(m =>{
				return { city_name: m };
			});
            userForm.user_state = props.user.user_state.map(m =>{
				return { state_name:m };
			});
            userForm.truck_type = props.user.truck_type.map(m =>{
				return { meta_value:m };
			});
            userForm.user_description = props.user.user_description;
        } else {
            Object.assign(userForm, initState);
        }
    })

    const initState = {
        name: '',
		last_name: '',
		email: '',
		phone: '',
		phone2: '',
		job_role: '',
		categories: [],
		user_city: [],
		user_state: [],
		truck_type: [],
		user_description: '',
    };

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

    const errors = ref({
        name: null,
        last_name: null,
        email: null,
        phone: null,
    })

    const formRef = ref(null);
    const loading = ref(false);

    const title = computed(() => {
        return (props.user) ? 'Editar usuario' : 'Crear usuario';
    });

    defineEmits(['reset-user']);

    const saveUser = () => {
        validations()

        console.log(errors);

        if(errors.value.name || errors.value.last_name || errors.value.email || errors.value.phone){
            console.log('Hay errores');
            return;
        } else {
            console.log(userForm);
        }
    }

    const validations = () => {
        errors.value = {
            name: userForm.name.length <= 4 ? 'Ingrese nombre' : null,
            last_name: userForm.name.length <= 1 ? 'Ingrese apellido' : null,
            email: !validateEmail(userForm.email) ? 'Ingrese email valido' : null,
            phone: userForm.phone.length < 10 ? 'Ingrese numero teléfonico valido' : null,
        };
    }
</script>

<template>
    <div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-labelledby="userModal" 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="btnCloseuserModal" 
                        type="button" 
                        @click="$emit('reset-user')"
                        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="saveUser" autocomplete="off" method="post" ref="formRef">
                        <CustomInput
                            label="Nombre(s)*"
                            name="name"
                            v-model:field="userForm.name"
                            :filled="false"
                            :error="errors.name"
                        />
                        <CustomInput
                            label="Apellido(s)*"
                            name="lastname"
                            :field="userForm.last_name"
                            :filled="false"
                            :error="errors.last_name"
                        />
                        <CustomInput
                            label="Teléfono 1*"
                            name="phone1"
                            :field="userForm.phone"
                            :filled="false"
                            type="number"
                            :error="errors.phone"
                        />
                        <CustomInput
                            label="Teléfono 2"
                            name="phone2"
                            type="number"
                            :field="userForm.phone2"
                            :filled="false"
                        />
                        <CustomInput
                            label="Correo electronico*"
                            name="email"
                            type="email"
                            :field="userForm.email"
                            :filled="false"
                            :error="errors.email"
                        />
                        <div class="mb-4 mt-3">
                            <label class="custom-label">Segmento</label>
                            <Segments
                                v-model="userForm.categories" 
                            />
                            <!-- <span class="error-msg" v-if="submited && errors.segment">{{ errors.segment }}</span> -->
                        </div>
                        <div class="mb-4 mt-3">
                            <label class="custom-label">Tipo de transporte que utiliza</label>
                            <TruckTypes
                                v-model="userForm.truck_type" 
                            />
                            <!-- <span class="error-msg" v-if="submited && errors.truckType">{{ errors.truckType }}</span> -->
                        </div>
                        <div class="mb-4 mt-3">
                            <label class="custom-label">Locaciones de carga por estado</label>
                            <States
                                v-model="userForm.user_state" 
                            />
                            <!-- <span class="error-msg" v-if="submited && errors.stateDestination">{{ errors.stateDestination }}</span> -->
                        </div>
                        <div class="mb-4 mt-3">
                            <label class="custom-label">Locaciones de carga por municipio</label>
                            <Cities
                                v-model="userForm.user_city" 
                            />
                            <!-- <span class="error-msg" v-if="submited && errors.cityDestination">{{ errors.cityDestination }}</span> -->
                        </div>
                        <div class="d-flex flex-column">
                            <label class="custom-label" for="description">Información adicional del usuario:</label>
                            <textarea 
                                class="custom-input-light"
                                name="description" 
                                id="description" 
                                placeholder="Escribe aqui..."
                                v-model="userForm.user_description"
                            ></textarea>
                        </div>
                        <div class="mt-4 text-center">
                            <Spiner v-if="loading"/>
                            <button 
                                v-else
                                class="btn btn-dark" type="submit">Guardar</button>
                        </div> 
                    </form>
                </div>
                <div class="modal-footer">
                    <button 
                        type="button" 
                        class="btn btn-dark" 
                        @click="$emit('reset-user')"
                        data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
    .form-content {
        margin: 0 auto;
        width: 80%;
    }
</style>