<script setup>
    import { reactive, ref } from 'vue';
    import CustomRadioInput from '../components/ui/CustomRadioInput.vue';
    import Custominput from '../components/ui/CustomInput.vue';
    import Segments from '../components/ui/Segments.vue';
    import States from '../components/ui/States.vue';
    import Cities from '../components/ui/Cities.vue';
    import TruckTypes from '../components/ui/TruckTypes.vue';
    import NotificationBadge from '../components/ui/NotificationBadge.vue';
    import {validRFC} from '../helpers/validations';
    import { useRouter } from 'vue-router';
    import { useNotificationsStore } from '../stores/notifications';
    import { useAuthStore } from '../stores/auth';
    import { complete_registry } from "../services/auth";
    import { updateMyUserProfile } from "../services/company"
    import Spiner from '../components/ui/Spiner.vue';
    import { useI18n } from 'vue-i18n';

    const notifications = useNotificationsStore();
    const auth = useAuthStore();
    const router = useRouter();
    const step = ref(1);
    const loading = ref(false);
    const msgError = ref('');
    const msgSuccess = ref('');

    const { t } = useI18n()

    const typeCompany = reactive({
        typeCompany: 'shipper',
        typeRFC: 'fisica'
    });

    const company = reactive({
        name: '',
        rfc: 'USAL950402D96',
        segments: [],
        states: [],
        cities: [],
        truckTypes: [],
        description: '',
    });

    const user = reactive({
        name: '',
        lastName: '',
        phone1: '',
        phone2: '',
    })

    const handleSelectedTypeCompany = () => {
        if(typeCompany.typeCompany === null || typeCompany.typeRFC === null) {
            msgError.value = t('errors.requireds');
            clearMessages();
            return;
        }
        console.log(typeCompany);
        step.value = 2;
    }

    const handleDataCompany = () => {
        const error = validatiosCompany();
        if(error != '') {
            msgError.value = error;
            clearMessages();
            return;
        }
        step.value = 3;
        // console.log(company);
    }

    const handleSendRegister = async () => {
        const error = validatiosUser();
        if(error != '') {
            msgError.value = error;
            clearMessages();
            return;
        }
        localStorage.setItem('access', auth.token);
        const companyData = {
            company_name : company.name,
            rfc : company.rfc,
            categories: company.segments.map((e) => e._id ),
            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,
            company_type : typeCompany.typeCompany,
        };
        loading.value = true;
        const result = await complete_registry( companyData );

        if(result.msg !== 'success') {
            msgError.value = result.msg;
            localStorage.removeItem('access');
            loading.value = false;
            clearMessages();
            return;
        }

        // console.log(result);
        localStorage.setItem('id', result.data._id);
        localStorage.setItem('session', auth.sesion);
        // localStorage.setItem('access', auth.token);

        const userData = {
            "first_name" : user.name,
            "last_name" : user.lastName,
            "phone" : user.phone1,
            "phone2" : user.phone2,
        };
        let respUser = await updateMyUserProfile( userData );
        // console.log('User create: ', respUser);
        if(respUser.msg === 'success') {
            auth.user = respUser.data;
        } else {
            auth.user = userData;
        }
        /////// Datos debug ///////
        notifications.show = true;
        notifications.text = t('messages.registerCompleted');

        loading.value = false;
        router.push({name: 'home'});
        ///////////////////////////
    }

    /// Falta el populate en la respuesta para completar el registro y luego de recargar la pagina

    const handleBack = (val) => {
        step.value = val;
    }

    const clearMessages = () => {
        setTimeout(() => {
            msgError.value = '';
            msgSuccess.value = '';
        }, 3000);
   }

   const validatiosCompany = () => {
        if(company.name.trim().length <= 2) {
            return t('errors.company');
        } else if(!validRFC(company.rfc, typeCompany.typeRFC)) {
            return t('errors.rfc')
        } else 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) {
            return t('errors.cities'); 
        } else if(company.truckTypes.length === 0) {
            return t('errors.trucks');
        } 
        else {
            return '';
        }
   }

   const validatiosUser = () => {
        if(user.name.trim().length < 3) {
            return t('errors.name');
        } else if(user.lastName.trim().length < 2) {
            return t('errors.lastname');
        } else if(user.phone1.trim().length < 10) {
            return t('errors.phone');
        } else {
            return '';
        }
   }

</script>

<template>
    <h2 class="title my-5">{{ t('login.completeRegister') }}</h2>

    <div class="card-info flex-column justify-content-center align-items-center mb-5">
        <form @submit.prevent="handleSelectedTypeCompany" v-if="step === 1" class="form-view">
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <h2 class="mt-4">{{ t('login.questionTypeCompany') }}*</h2>
            <CustomRadioInput
                value="shipper" 
                :label="t('global.shipper')"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="carrier" 
                :label="t('global.carrier')"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="b-shipper" 
                :label="t('global.brokerShipper')"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="b-carrier" 
                :label="t('global.brokerCarrier')"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />

            <h2 class="mt-5">{{ t('login.questionFiscal') }}*</h2>
            <CustomRadioInput
                value="fisica" 
                label="Persona fisica"
                name="type-rfc"
                v-model:typeselected="typeCompany.typeRFC"
            />
            <CustomRadioInput
                value="moral" 
                label="Persona moral"
                name="type-rfc"
                v-model:typeselected="typeCompany.typeRFC"
            />

            <input type="submit" :value="t('buttons.continue')" class="btn-primary-lg btn-lg-block my-4">
        </form>
        <form @submit.prevent="handleDataCompany" v-if="step === 2">
            <div class="d-flex justify-content-center align-items-center my-4">
                <a  
                    @click="handleBack(1)"
                    class="btn-text ms-2"><i class="fa-solid fa-arrow-left"></i> {{ t('buttons.back') }}</a>
            </div>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <h2>{{ t('login.companyData') }}</h2>
            <div class="divider mt-2 mb-4"></div>
            <Custominput
                type="text"
                :label="t('labels.questionCompany') + '*'"
                name="name"
                :filled="false"
                v-model:field="company.name"
            />
            <Custominput
                :label="t('labels.questionRfc') + '*'"
                type="text"
                name="rfc"
                :filled="false"
                v-model:field="company.rfc"
            />
            <div class="mb-4">
                <label class="custom-label">{{ t('labels.questionSegments') }} *</label>
                <Segments 
                    v-model="company.segments" 
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">{{ t('labels.questionSates') }} *</label>
                <States 
                    v-model="company.states"
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">{{ t('labels.questionCities') }} *</label>
                <Cities 
                    v-model="company.cities"
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">{{ t('labels.questionTrucks') }} *</label>
                <TruckTypes 
                    v-model="company.truckTypes"
                    :multiple="true"
                />
            </div>
            <Custominput
                :label="t('labels.infoCompanies')"
                type="text"
                name="description"
                :filled="false"
                v-model:field="company.description"
            />

            <input type="submit" :value="t('buttons.continue')" class="btn-primary-lg btn-lg-block my-4">
        </form>
        <form @submit.prevent="handleSendRegister" v-if="step === 3" class="form-view">
            <div class="d-flex justify-content-center align-items-center mb-4">
                <a  
                    @click="handleBack(2)"
                    class="btn-text ms-2"><i class="fa-solid fa-arrow-left"></i> {{ t('buttons.back') }}</a>
            </div>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <h2>{{ t('global.infoUser') }}</h2>
            <div class="divider mt-2 mb-4"></div>
            <Custominput
                :label=" t('labels.names') +'*'"
                type="text"
                name="name"
                :filled="false"
                v-model:field="user.name"
            />
            <Custominput
            :label=" t('labels.lastnames') +'*'"
                type="text"
                name="lastname"
                :filled="false"
                v-model:field="user.lastName"
            />
            <div class="content-phone">
                <Custominput
                    :label=" t('labels.phone1') +'*'"
                    type="number"
                    name="phone1"
                    :step="1"
                    :filled="false"
                    v-model:field="user.phone1"
                />
                <Custominput
                :label=" t('labels.phone2')"
                    type="number"
                    name="phone2"
                    :step="1"
                    :filled="false"
                    v-model:field="user.phone2"
                />
            </div>
            <Spiner v-if="loading" class="mt-5"/>
            <input 
                v-else 
                type="submit" 
                value="Guardar" 
                class="btn-primary-lg btn-lg-block my-4"
            />
        </form>
    </div>
</template>

<style lang="scss" scoped>
  .content-phone{
    display: flex;
    flex-direction: row;
    gap: 5rem;
  }

  .form-view {
    min-width: 300px;
  }

  @media (max-width: 568px) {
    .content-phone{
        flex-direction: column;
        gap: 1rem
    }
  }
</style>


<!-- ¿Como te quieres registrar? (Opciones a elegir)
1 - Embarcador
2 - Transportista
3 - Broker (Embarcador)
4 - Broker (Transportista) -->