<script setup>
    import { reactive, ref, onMounted, watch } from 'vue';
    import { useLoadsStore } from '../stores/loads';
    import Custominput from './ui/custominput.vue';
    import Segments from './ui/Segments.vue';
    import TruckTypes from './ui/TruckTypes.vue';
    import Cities from './ui/Cities.vue';
    import States from './ui/States.vue';
    import Spiner from './ui/Spiner.vue';
    import Products from './ui/Products.vue';
    import { GoogleMap, Marker, Polyline } from "vue3-google-map";
    import useDirectionsRender from '../composables/useDirectionRender';
    import { useAuthStore } from '../stores/auth';
    import Swal from 'sweetalert2';
    import { useNotificationsStore } from '../stores/notifications';

    const loadStore = useLoadsStore();
    const notyStore = useNotificationsStore();
    const auth = useAuthStore();
    const windowWidth = ref(window.innerWidth);
    const zoom = ref(6);
    const heightMap = ref(768);
    const originCoords = ref(null);
    const destinationCoords = ref(null);
    const startLocation = ref(null);
    const endLocation = ref(null);
    const isLoading = ref(false);
    const submited = ref(false);
    const { geocodeAddress } = useDirectionsRender();
    const formRef = ref(null);
    const errors = ref({
        segment: null,
        product: null,
        truckType: null,
        cityOrigin: null,
        stateOrigin: null,
        cityDestination: null,
        stateDestination: null,
    });

    
    const clearLoad = () => {
        loadStore.currentLoad = null;
        loadStore.openModalEdit = false;
    }

    const handleResize = () => {
        windowWidth.value = window.innerWidth
        if(windowWidth.value <= 1024){
            zoom.value = 4
            heightMap.value = 420;
        } else {
            zoom.value = 6;
            heightMap.value = 768;
        }
    }

    onMounted(() => {
        window.addEventListener('resize', handleResize);
        // mapRef.value = this.$refs.myMap;
        if(window.innerWidth <= 1024) {
            zoom.value = 4;
            heightMap.value = 420;
        }
        formLoad.owner = auth.user?.first_name + ' ' + auth.user?.last_name;
        //origin_formatted_address
        if(loadStore.currentLoad){
            formLoad.price = loadStore.currentLoad.actual_cost;
			formLoad.segment = loadStore.currentLoad.categories.map(m =>{
				return m;
			});
            startLocation.value = loadStore.currentLoad.origin_formatted_address;
            endLocation.value = loadStore.currentLoad.destination_formatted_address;
			formLoad.terms = loadStore.currentLoad.product;
            formLoad.owner = loadStore.currentLoad.posted_by_name;
            formLoad.notes = loadStore.currentLoad.notes;
            formLoad.weight = loadStore.currentLoad.weight;
            formLoad.dateLoad = loadStore.currentLoad.est_loading_date?.substring(0, 10);
            formLoad.dateDownload = loadStore.currentLoad.est_unloading_date?.substring(0, 10);
            formLoad.truckType = {meta_value: loadStore.currentLoad.truck_type};

            origin.locationName =  loadStore.currentLoad.origin.company_name;
            origin.address =  loadStore.currentLoad.origin.street_address1;
            origin.state =  { state_name: loadStore.currentLoad.origin.state };
            origin.city =  { city_name: loadStore.currentLoad.origin.city };
            origin.country = loadStore.currentLoad.origin.country;
            origin.postalCode = loadStore.currentLoad.origin.zipcode;
            origin.ref = loadStore.currentLoad.origin.landmark;

            destination.locationName =  loadStore.currentLoad.destination.company_name;
            destination.address =  loadStore.currentLoad.destination.street_address1;
            destination.state =  { state_name: loadStore.currentLoad.destination.state };
            destination.city =  { city_name: loadStore.currentLoad.destination.city };
            destination.country = loadStore.currentLoad.destination.country;
            destination.postalCode = loadStore.currentLoad.destination.zipcode;
            destination.ref = loadStore.currentLoad.destination.landmark;
            getCoordsMap();
		}

        watch(origin, async() => {
            // console.log(origin);
            if(origin.address && origin.city && origin.state) {
                startLocation.value = origin.address + ', ' + origin.city.city_name + ', ' + origin.state.state_name + ', ' + origin.country + ', ' +origin.postalCode;
                originCoords.value = await geocodeAddress(startLocation.value);
                // console.log('Origin:')
                // console.log(originCoords.value)
            }
        })

        watch(destination, async() => {
            if(destination.address && destination.city && destination.state) {
                endLocation.value = destination.address + ', ' + destination.city.city_name + ', ' + destination.state.state_name + ', ' + destination.country + ', ' +destination.postalCode;
                destinationCoords.value = await geocodeAddress(endLocation.value);
                // console.log('Destination:')
                // console.log(destinationCoords.value);
            }
        })
    })

    const getCoordsMap = async() => {
        if(loadStore.currentLoad.origin_formatted_address) {
            originCoords.value = await geocodeAddress(loadStore.currentLoad.origin_formatted_address);
        }
        if(loadStore.currentLoad.destination_formatted_address){
            destinationCoords.value = await geocodeAddress(loadStore.currentLoad.destination_formatted_address);
        }
    }


    const formLoad = reactive({
        dateLoad: '',
        dateDownload: '',
        segment: [],
        truckType: [],
        terms: [],
        price: 0,
        weight: 0,
        notes: '',
        owner: '',
    });

    const origin = reactive({
        locationName: '',
        address: '',
        state: '',
        city: '',
        country: '',
        postalCode: '',
        ref: '',
    });

    const destination = reactive({
        locationName: '',
        address: '',
        state: '',
        city: '',
        country: '',
        postalCode: '',
        ref: '',
    });

    const setLoadData = () => {
        let loadData = {
			actual_cost: formLoad.price,
			truck_type: formLoad.truckType.meta_value || null,
			est_loading_date : formLoad.dateLoad,
			est_unloading_date : formLoad.dateDownload,
			notes : formLoad.notes,
			weight : formLoad.weight,
			product: formLoad.terms.length <= 0 ? null : formLoad.terms,
			categories: formLoad.segment || null,
			origin:{
                company_name : origin.locationName,
				street_address1 : origin.address,
				state : origin.state.state_name,
				city : origin.city.city_name,
				country : origin.country,
				landmark : origin.ref,
				zipcode : origin.postalCode,
                lat : originCoords.value?.lat,
                lng : originCoords.value?.lng
			},
			destination:{
                company_name : destination.locationName,
				street_address1 : destination.address,
				state : destination.state.state_name,
				city : destination.city.city_name,
				country : destination.country,
				landmark : destination.ref,
				zipcode : destination.postalCode,
                lat : destinationCoords.value?.lat,
                lng : destinationCoords.value?.lng
			},
			company: auth.user.company,
            posted_by: auth.user._id,
            posted_by_name: formLoad.owner
		};

        return loadData;
    }

    const updateLoad = async(loadData) => {
        isLoading.value = true;
        if(loadStore.currentLoad){
            const resp = await loadStore.updateLoad(loadStore.currentLoad._id, loadData);
            isLoading.value = false;
            if(resp) {
                const index = loadStore.loads.findIndex((load) => load._id === resp._id);
                loadStore.loads[index] = {
                    ...loadStore.loads[index],
                    ...resp
                };
                return 'success';
            } else {
                return 'error';
            }
		} else{
            const resp = await loadStore.saveLoad(loadData);
            isLoading.value = false;
            if(resp) {
                loadStore.loads.push({
                    ...resp,
                    ...loadData
                });
                return 'success';
            } else {
                return 'error';
            }
		}
    }

    const handleSave = async() => {
        submited.value = false;
        const loadData = setLoadData();
        const resp = await updateLoad(loadData);
        if(resp === 'success') {
            notyStore.show = 'true';
            notyStore.text = 'Carga guardada!'
            document.getElementById('btnCloseFormLoadModal').click();
        } else {
            Swal.fire({
                title: "Error!",
                text: "No se pudo guardar carga, intente más tarde",
                icon: "error"
            });
        }
    }

    const validations = () => {
        errors.value = {
            segment: formLoad.segment.length <= 0 ? 'Seleccione segmento' : null,
            product: formLoad.terms.length <= 0 ? 'Seleccione producto' : null,
            truckType: formLoad.truckType.length <= 0 ? 'Seleccione tipo de transporte' : null,
            cityOrigin: origin.city.length <= 0 ? 'Seleccione ciudad' : null,
            stateOrigin: origin.state.length <= 0 ? 'Seleccione estado' : null,
            cityDestination: destination.city.length <= 0 ? 'Seleccione ciudad' : null,
            stateDestination: destination.state.length <= 0 ? 'Seleccione estado' : null,
        };
    }


    const handlePostLoad = async() => {
        submited.value = true;
        let loadData = setLoadData();

        loadData = {
            ...loadData,
            status: "Published",
            load_status: "Published"
        }

        setTimeout(async() => {
            const formValid = formRef.value.checkValidity();
            validations()
            console.log(formValid);
            if(formValid){
                const hasError = Object.values(errors.value).some(val => val != null);
                console.log(hasError);
                if(!hasError) {
                    const resp = await updateLoad(loadData);
                    if(resp === 'success') {
                        notyStore.show = 'true';
                        notyStore.text = 'Carga publicada!'
                        document.getElementById('btnCloseFormLoadModal').click();
                    } else {
                        Swal.fire({
                            title: "Error!",
                            text: "No se pudo publicar carga, intente más tarde",
                            icon: "error"
                        });
                    }
                } else {
                    console.log('Hay errores');
                }
            }
        }, 200)
        
    }
</script>

<template>
    <div class="modal fade" id="formLoadModal" tabindex="-1" role="dialog" aria-labelledby="formLoadModal" aria-hidden="true">
        <div class="modal-dialog modal-fullscreen modal-dialog-centered" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h2 class="title mt-2 mb-3">Crear nueva carga</h2>
                <button 
                    id="btnCloseFormLoadModal" 
                    type="button" 
                    class="close bg-white" 
                    data-dismiss="modal" 
                    @click="clearLoad"
                    aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form class="form-content" ref="formRef">
                    <div class="form-box">
                        <div class="form-section">
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Segmento*</label>
                                <Segments
                                    v-model="formLoad.segment" 
                                />
                                <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*</label>
                                <TruckTypes
                                    v-model="formLoad.truckType" 
                                />
                                <span class="error-msg" v-if="submited && errors.truckType">{{ errors.truckType }}</span>
                            </div>
                            <Custominput
                                label="Fecha de carga*"
                                type="date"
                                :filled="false"
                                name="date-load"
                                :required="submited ? true : false"
                                :error="(submited && !formLoad.dateLoad) ? 'Fecha es requerida' : null"
                                v-model:field="formLoad.dateLoad"
                            />
                            <Custominput
                                label="Fecha de descarga*"
                                type="date"
                                :filled="false"
                                name="date-download"
                                :required="submited ? true : false"
                                :error="(submited && !formLoad.dateDownload) ? 'Fecha es requerida' : null"
                                v-model:field="formLoad.dateDownload"
                            />
                            <Custominput
                                label="Peso de la carga*"
                                type="number"
                                :filled="false"
                                name="weight"
                                :required="submited ? true : false"
                                :error="(submited && !formLoad.weight) ? 'Ingrese peso en KG' : null"
                                v-model:field="formLoad.weight"
                            />
                        </div>
                        <div class="form-section">
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Terminos*</label>
                                <Products
                                    v-model="formLoad.terms" 
                                />
                                <span class="error-msg" v-if="submited && errors.product">{{ errors.product }}</span>
                            </div>
                            <Custominput
                                label="Precio*"
                                type="Number"
                                :filled="false"
                                name="price"
                                v-model:field="formLoad.price"
                                :required="submited ? true : false"
                                :error="(submited && !formLoad.price) ? 'Ingrese precio en MXN' : null"
                            />
                            <Custominput
                                label="Notas"
                                type="text"
                                :filled="false"
                                name="notes"
                                v-model:field="formLoad.notes"
                            />
                            <Custominput
                                label="Publicación hecha por*"
                                type="text"
                                :filled="false"
                                :readonly="true"
                                name="owner"
                                v-model:field="formLoad.owner"
                            />
                        </div>
                    </div>
                    <div class="form-box">
                        <div class="form-section">
                            <h2>Dirección de origen</h2>
                            <Custominput
                                label="Nombre locación de carga*"
                                type="text"
                                :filled="false"
                                name="name-location-origin"
                                v-model:field="origin.locationName"
                                :required="submited ? true : false"
                                :error="(submited && !origin.locationName) ? 'Ingrese nombre' : null"
                            />
                            <Custominput
                                label="Dirección*"
                                type="text"
                                :filled="false"
                                name="address-origin"
                                v-model:field="origin.address"
                                :required="submited ? true : false"
                                :error="(submited && !origin.address) ? 'Ingrese dirección' : null"
                            />
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Ciudad*</label>
                                <Cities
                                    v-model="origin.city" 
                                />
                                <span class="error-msg" v-if="submited && errors.cityOrigin">{{ errors.cityOrigin }}</span>
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Estado*</label>
                                <States
                                    v-model="origin.state" 
                                />
                                <span class="error-msg" v-if="submited && errors.stateOrigin">{{ errors.stateOrigin }}</span>
                            </div>
                            <Custominput
                                label="País*"
                                type="text"
                                :filled="false"
                                name="country-origin"
                                v-model:field="origin.country"
                                :required="submited ? true : false"
                                :error="(submited && !origin.country) ? 'Ingrese país' : null"
                            />
                            <Custominput
                                label="Código Postal*"
                                type="text"
                                :filled="false"
                                name="postalCode-origin"
                                v-model:field="origin.postalCode"
                                :required="submited ? true : false"
                                :error="(submited && !origin.postalCode) ? 'Ingrese Código postal' : null"
                            />
                            <Custominput
                                label="Punto de referencia"
                                type="text"
                                :filled="false"
                                name="ref-origin"
                                v-model:field="origin.ref"
                            />
                        </div>
                        <div class="form-section">
                            <h2>Dirección de destino</h2>
                            <Custominput
                                label="Nombre locación de descarga*"
                                type="text"
                                :filled="false"
                                name="name-location-destination"
                                v-model:field="destination.locationName"
                                :required="submited ? true : false"
                                :error="(submited && !destination.locationName) ? 'Ingrese nombre' : null"
                            />
                            <Custominput
                                label="Dirección"
                                type="text"
                                :filled="false"
                                name="address-destination"
                                v-model:field="destination.address"
                                :required="submited ? true : false"
                                :error="(submited && !destination.address) ? 'Ingrese dirección' : null"
                            />
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Ciudad*</label>
                                <Cities
                                    v-model="destination.city" 
                                />
                                <span class="error-msg" v-if="submited && errors.cityDestination">{{ errors.cityDestination }}</span>
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Estado*</label>
                                <States
                                    v-model="destination.state" 
                                />
                                <span class="error-msg" v-if="submited && errors.stateDestination">{{ errors.stateDestination }}</span>
                            </div>
                            <Custominput
                                label="País*"
                                type="text"
                                :filled="false"
                                name="country-destination"
                                v-model:field="destination.country"
                                :required="submited ? true : false"
                                :error="(submited && !destination.country) ? 'Ingrese país' : null"
                            />
                            <Custominput
                                label="Código Postal*"
                                type="text"
                                :filled="false"
                                name="postalCode-destination"
                                v-model:field="destination.postalCode"
                                :required="submited ? true : false"
                                :error="(submited && !destination.postalCode) ? 'Ingrese código postal' : null"
                            />
                            <Custominput
                                label="Punto de referencia"
                                type="text"
                                :filled="false"
                                name="ref-destination"
                                v-model:field="destination.ref"
                            />
                        </div>
                    </div>
                </form>
                <GoogleMap
                    api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs"
                    :center="{lat:19.432600, lng:-99.133209}"
                    :zoom="zoom" 
                    :min-zoom="2"
                    :max-zoom="12"
                    :style="{width: 100 + '%', height: heightMap + 'px'}"
                    :options="{
                        zoomControl: true,
                        mapTypeControl: true,
                        scaleControl: true,
                        streetViewControl: true,
                        rotateControl: true,
                        fullscreenControl: true
                    }"
                > 
                    <Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
                    <Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
                    <!-- <Polyline :options="{
                        path: polyline,
                        // geodesic: true,
                        strokeColor: '#FF0000',
                        strokeOpacity: 1.0,
                        strokeWeight: 2
                    }" /> -->
                </GoogleMap>
            </div>
            <div class="modal-footer custom-footer">
                <Spiner v-if="isLoading"/>
                <div v-else class="btns-footer">
                    <button 
                        type="button" 
                        class="btn btn-dark" 
                        @click="clearLoad"
                        data-dismiss="modal">Cerrar</button>
                    <button 
                        type="button" 
                        class="btn btn-dark" 
                        @click="handleSave"
                    >Guardar</button>
                    <button 
                        type="submit" 
                        @click.prevent="handlePostLoad"
                        class="btn-primary-sm radius-sm" 
                    >Publicar</button>
                </div>
            </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
    .form-content {
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-content: center;
        align-items: center;
        margin: 0 auto;
    }

    .form-box {
        width: 80%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        gap: 4rem;
    }

    .form-section {
        width: 100%;
    }

    .custom-footer {
        display: flex;
        justify-content: center;
    }

    .error-msg {
        color: red;
        font-size: 12px;
        font-weight: 300;
    }

    .btns-footer {
        display: flex;
        gap: 1rem;
    }

    .radius-sm{
        border-radius: 5px;
    }

    @media (max-width: 1024px) {
        .form-box {
            width: 95%;
            gap: 2rem;
        }
    }

    @media (max-width: 568px) {
        .form-box {
            width: 100%;
            flex-direction: column;
            gap: 2rem;
        }
    }
</style>