<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"

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

    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 = 'Todos los campos con obligatorios';
            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;
        }
        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,
        };
        const result = await complete_registry( companyData );
        console.log(result);
        if(result.msg === 'success' && result.data !== null){
            localStorage.setItem('id', result.data._id);
        }

        const userData = {
            "first_name" : user.name,
            "last_name" : user.lastName,
            "phone" : user.phone1,
            "phone2" : user.phone2,
        };
        await updateMyUserProfile( userData );
        /////// Datos debug ///////
        notifications.show = true;
        notifications.text = 'Los datos se llenaron correctamente';
        localStorage.setItem('session', 'jssksksksk2skskkskskkskss');
        auth.$patch({
            sesion: 'jssksksksk2skskkskskkskss',
            token: 'jkdkdkdkeoee00kelldd',
            user: {
                first_name: user.name,
                last_name: user.lastName
            },
        })
        router.push({name: 'home'});
        ///////////////////////////
    }

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

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

   const validatiosCompany = () => {
        if(company.name.trim().length <= 2) {
            return 'Ingresa nombre de empresa valido';
        } else if(!validRFC(company.rfc, typeCompany.typeRFC)) {
            return 'Ingresa RFC valido';
        } else if(company.segments.length === 0) {
            return 'Selecciona al menos un segmento';
        } else if(company.states.length === 0) {
            return 'Selecciona al menos un estado';
        } else if(company.cities.length === 0) {
            return 'Selecciona al menos un municipio'; 
        } else if(company.truckTypes.length === 0) {
            return 'Selecciona al menos un tipo de transporte';
        } 
        else {
            return '';
        }
   }

   const validatiosUser = () => {
        if(user.name.trim().length < 3) {
            return 'Ingresa nombre(s) valido';
        } else if(user.lastName.trim().length < 2) {
            return 'Ingresa apellido(s) valido';
        } else if(user.phone1.trim().length < 10) {
            return 'Ingresa teléfono valido';
        } else {
            return '';
        }
   }

</script>

<template>
    <h2 class="title my-5">Complete su registro</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">¿Como te quieres registrar?*</h2>
            <CustomRadioInput
                value="shipper" 
                label="Embarcador"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="carrier" 
                label="Transportista"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="b-shipper" 
                label="Broker (Embarcador)"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />
            <CustomRadioInput
                value="b-carrier" 
                label="Broker (Transportista)"
                name="type-company"
                v-model:typeselected="typeCompany.typeCompany"
            />

            <h2 class="mt-5">¿Como trabajas?*</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="Continuar" 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> Volver</a>
            </div>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <h2>Datos de la empresa</h2>
            <div class="divider mt-2 mb-4"></div>
            <Custominput
                label="¿Cuál es el nombre de la empresa? *"
                type="text"
                name="name"
                :filled="false"
                v-model:field="company.name"
            />
            <Custominput
                label="¿Cuál es el RFC de la empresa? *"
                type="text"
                name="rfc"
                :filled="false"
                v-model:field="company.rfc"
            />
            <div class="mb-4">
                <label class="custom-label">¿A que segmentos pertenece la empresa? *</label>
                <Segments 
                    v-model="company.segments" 
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">¿Cuáles son las locaciones de carga de la empresa por estado? *</label>
                <States 
                    v-model="company.states"
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">¿Cuáles son las locaciones de carga de la empresa por municipio? *</label>
                <Cities 
                    v-model="company.cities"
                    :multiple="true"
                />
            </div>
            <div class="mb-4">
                <label class="custom-label">¿Qué tipo de transportes utiliza la empresa? *</label>
                <TruckTypes 
                    v-model="company.truckTypes"
                    :multiple="true"
                />
            </div>
            <Custominput
                label="Información adicional de la empresa:"
                type="text"
                name="description"
                :filled="false"
                v-model:field="company.description"
            />

            <input type="submit" value="Continuar" 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> Volver</a>
            </div>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <h2>Información personal</h2>
            <div class="divider mt-2 mb-4"></div>
            <Custominput
                label="Nombres(s):"
                type="text"
                name="name"
                :filled="false"
                v-model:field="user.name"
            />
            <Custominput
                label="Apellidos(s):"
                type="text"
                name="lastname"
                :filled="false"
                v-model:field="user.lastName"
            />
            <div class="content-phone">
                <Custominput
                    label="Teléfono 1: *"
                    type="number"
                    name="phone1"
                    :filled="false"
                    v-model:field="user.phone1"
                />
                <Custominput
                    label="Teléfono 2:"
                    type="number"
                    name="phone2"
                    :filled="false"
                    v-model:field="user.phone2"
                />
            </div>

            <input 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) -->