<script setup>
    import { onMounted, reactive, ref } from 'vue';
    import Spiner from '../ui/Spiner.vue';
    import Cities from './Cities.vue';
    import NotificationBadge from './NotificationBadge.vue';
    import Segments from './Segments.vue';
    import States from './States.vue';
    import TruckTypes from './TruckTypes.vue';
    import Custominput from './custominput.vue';
    import { useCompanyStore } from '../../stores/company';
    import { useNotificationsStore } from '../../stores/notifications';

    const companyStore = useCompanyStore()
    const notifications = useNotificationsStore()

    console.log(companyStore.company?.categories);

    const loading = ref(false);
    const msgError = ref('');
    const companyCategories = ref([]);
    const companyStates = ref([]);
    const companyCity = ref([]);
    const companyTruckType = ref([]);

    onMounted(() => {
        if(companyStore.company){
			companyCategories.value = companyStore.company.categories;
		}
        if(companyStore.company){
			companyStates.value = companyStore.company.company_state.map(m =>{
				return { state_name: m };
			});
		}
        if(companyStore.company){
			companyCity.value = companyStore.company.company_city.map(m =>{
				return { city_name: m };
			});
		}
        if(companyStore.company){
			companyTruckType.value = companyStore.company.truck_type.map(m =>{
				return { meta_value: m };
			});
		}
    })
    const company = reactive({
        segments: companyCategories,
        states: companyStates,
        cities: companyCity,
        truckTypes: companyTruckType,
        description: companyStore.company?.company_description ?? '',
    });

    const handleSave = async() => {
        // const resp = editCompany()
        const resp = validations();
        if(resp !== '') {
            msgError.value = resp;
            clearMessages();
        } else {
            loading.value = true;
            let companyData = {
                is_company: companyStore.company._id,
                company_type: companyStore.company.company_type,
                meta_data: companyStore.company.meta_data,
                categories: company.segments,
                company_city: company.cities.map((e) => e.city_name),
                company_state: company.states.map((e) => e.state_name),
                truck_type: company.truckTypes.map((e) => e.meta_value),
                company_description: company.description
            };
            const result = await companyStore.editCompany(companyData);
            loading.value = false;
            if(result === 'success') {
                document.getElementById('btnCloseEditCompany').click();
                notifications.show = true;
                notifications.text = 'Empresa actualizada';
            } else {
                msgError.value === result;
                clearMessages();
            }
        }
    }

    const clearMessages = () => {
        setTimeout(() => {
            msgError.value = '';
        }, 3000);
   }
    
    const validations = () => {
        if(company.segments.length === 0) {
            return 'Agregue al menos un segmento';
        }else if(company.states.length === 0) {
            return 'Agregue al menos un estado';
        } else if( company.cities.length === 0) {
            msgError.value = 'Agregue al menos una ciudad';
        } else if(company.truckTypes.length === 0){
            msgError.value = 'Agregue al menos un tipo de camión';
        } else {
            return '';
        }
        
    }


</script>

<template>
   <div class="modal fade" id="editcompanymodal" tabindex="-1" role="dialog" aria-labelledby="editcompany" 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">Editar Empresa</h2>
                <button id="btnCloseEditCompany" type="button" class="close bg-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form @submit.prevent="handleSave" class="view-form">
                    <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
                    <div class="mb-4 mt-3">
                        <label class="custom-label">Segmento de la empresa</label>
                        <Segments
                            v-model="company.segments" 
                            :multiple="true"
                        />
                    </div>
                    <div class="mb-4">
                        <label class="custom-label">Ubicaciones de carga por estado</label>
                        <States
                            v-model="company.states"
                            :multiple="true"
                        />
                    </div>
                    <div class="mb-4">
                        <label class="custom-label">Ubicaciones de carga por municipio</label>
                        <Cities 
                            v-model="company.cities"
                            :multiple="true"
                        />
                    </div>
                    <div class="mb-4">
                        <label class="custom-label">Tipo de transportes que utiliza</label>
                        <TruckTypes 
                            v-model="company.truckTypes"
                            :multiple="true"
                        />
                    </div>
                    <Custominput
                        label="Descripción de la empresa:"
                        type="text"
                        name="description"
                        :filled="false"
                        v-model:field="company.description"
                    />
                    <Spiner v-if="loading"/>
                    <input 
                        v-else
                        type="submit" 
                        value="Cuardar cambios" class="btn-primary-lg btn-lg-block my-4">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-dark" data-dismiss="modal">Cerrar</button>
            </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
    /* .modal-width{
        width: 1500px !important;
    } */

    .view-form {
        padding: 1rem 4rem;
    }
</style>