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

    const companyStore = useCompanyStore()
    const notifications = useNotificationsStore()
    const loading = ref(false);
    const msgError = ref('');
    const companyCategories = ref([]);
    const companyStates = ref([]);
    const companyCity = ref([]);
    const companyTruckType = ref([]);
    const { t } = useI18n()

    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.map((e) => e),
                // 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
            };
            // console.log( companyData )
            const result = await companyStore.editCompany(companyData);
            loading.value = false;
            if(result === 'success') {
                document.getElementById('btnCloseEditCompany').click();
                notifications.show = true;
                notifications.text = t('messages.updateCompany');
            } else {
                msgError.value === result;
                clearMessages();
            }
        }
    }

    const clearMessages = () => {
        setTimeout(() => {
            msgError.value = '';
        }, 3000);
   }
    
    const validations = () => {
        if(company.segments.length === 0) {
            return t('errors.segments');
        // }else if(company.states.length === 0) {
        //     return t('errors.states');
        // } else if( company.cities.length === 0) {
        //     msgError.value = t('errors.cities');
        } else if(company.truckTypes.length === 0){
            msgError.value = t('errors.trucks');
        } 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">{{ t('company.edit') }}</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">{{ t('labels.segmentsCompany') }}</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">{{  t('labels.truckUsed') }}</label>
                        <TruckTypes 
                            v-model="company.truckTypes"
                            :multiple="true"
                        />
                    </div>
                    <Custominput
                        :label=" t('labels.infoCompany')"
                        type="text"
                        name="description"
                        :filled="false"
                        v-model:field="company.description"
                    />
                    <Spiner v-if="loading"/>
                    <input 
                        v-else
                        type="submit" 
                        :value="t('buttons.save')" 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">{{t('buttons.close')}}</button>
            </div>
            </div>
        </div>
    </div>
</template>

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

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