<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';
    import { useAuthStore } from '../stores/auth';
    import { useCompanyStore } from '../stores/company';
    import Swal from 'sweetalert2';

    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 authStore = useAuthStore();
    const companyStore = useCompanyStore();

    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 = async() => {
        validations()
        if(errors.value.name || errors.value.last_name || errors.value.email || errors.value.phone){
            return;
        } else {
            let userData ={
				first_name: userForm.name,
				last_name: userForm.last_name,
				email: userForm.email,
				phone: userForm.phone,
				phone2: userForm.phone2,
				job_role: userForm.job_role,
				permissions: authStore.user.permissions,
				company: authStore.user.company,
				categories: userForm.categories.length <= 0 ? null : userForm.categories?.map((e) => e._id),
				user_city: userForm.user_city?.length <= 0 ? null : userForm.user_city?.map((e) => e.city_name),
				user_state: userForm.user_state?.length <= 0 ? null : userForm.user_state?.map((e) => e.state_name),
				truck_type: userForm.truck_type?.length <= 0 ? null : userForm.truck_type?.map((e) => e.meta_value),
				user_description: userForm.user_description
			}

            const dataUpdate = {
                categories: userForm.categories,
                name: userForm.name + ' ' + userForm.last_name
            }

            let result = 'error';
            let action = 'Creado';
            loading.value = true;
            if(props.user !== null) {
                // Se actualiza
                result = await companyStore.updateUserCompany(props.user._id, userData, dataUpdate);
                action = 'actualizado';
            } else {
                // Se crea
                result = await companyStore.createUserCompany(userData, dataUpdate);
                action = 'creado';
            }
            loading.value = false;
            if(result === 'success') {
                document.getElementById('btnCloseuserModal').click();
                Swal.fire({
                    title: `<strong>Usuario ${action} con éxito!</strong>`,
                    icon: 'success'
                })
            } else {
                Swal.fire({
                    title: result,
                    icon: 'error'
                })
            }
        }
    }

    const validations = () => {
        errors.value = {
            name: userForm.name.length < 4 ? 'Ingrese nombre' : null,
            last_name: userForm.last_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"
                            v-model:field="userForm.last_name"
                            :filled="false"
                            :error="errors.last_name"
                        />
                        <CustomInput
                            label="Teléfono 1*"
                            name="phone1"
                            type="number"
                            v-model:field="userForm.phone"
                            :filled="false"
                            :error="errors.phone"
                        />
                        <CustomInput
                            label="Teléfono 2"
                            name="phone2"
                            type="number"
                            v-model:field="userForm.phone2"
                            :filled="false"
                        />
                        <CustomInput
                            label="Correo electronico*"
                            name="email"
                            type="email"
                            v-model:field="userForm.email"
                            :filled="false"
                            :error="errors.email"
                        />
                        <div class="d-flex flex-column">
                            <label class="custom-label" for="role">Rol de usuario:</label>
                            <select 
                                class="custom-input-light"
                                name="role" 
                                id="role" 
                                v-model="userForm.job_role"
                            >
                                <option disabled value="">-- Seleccionar rol --</option>
                                <option value="owner">Dueño</option>
                                <option value="manager">Gerente</option>
                                <option v-if="authStore.user?.permissions.includes('role_carrier')" value="driver">Conductor</option>
                            </select>
                        </div>
                        <div class="mb-4 mt-3">
                            <label class="custom-label">Segmento</label>
                            <Segments
                                v-model="userForm.categories" 
                                :multiple="true"
                            />
                            <!-- <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" 
                                :multiple="true"
                            />
                            <!-- <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" 
                                :multiple="true"
                            />
                            <!-- <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" 
                                :multiple="true"
                            />
                            <!-- <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>