<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';

    const loadStore = useLoadsStore();
    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 { geocodeAddress } = useDirectionsRender();

    
    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 handleSave = async() => {
        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 || null,
			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
		};

        console.log('loadData: ', loadData);
        isLoading.value = true;
        if(loadStore.currentLoad){
            const resp = await loadStore.updateLoad(loadStore.currentLoad._id, loadData);
			const index = loadStore.loads.findIndex((load) => load._id === resp._id);
            isLoading.value = false;
            loadStore.loads[index] = resp;
            document.getElementById('btnCloseFormLoadModal').click();
		} else{
            const resp = await loadStore.saveLoad(loadData);
            isLoading.value = false;
            loadStore.loads.unshift(resp);
            document.getElementById('btnCloseFormLoadModal').click();
		}
    }
</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">
                    <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" 
                                />
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Tipo de transporte*</label>
                                <TruckTypes
                                    v-model="formLoad.truckType" 
                                />
                            </div>
                            <Custominput
                                label="Fecha de carga*"
                                type="date"
                                :filled="false"
                                name="date-load"
                                v-model:field="formLoad.dateLoad"
                            />
                            <Custominput
                                label="Fecha de descarga*"
                                type="date"
                                :filled="false"
                                name="date-download"
                                v-model:field="formLoad.dateDownload"
                            />
                            <Custominput
                                label="Peso de la carga*"
                                type="number"
                                :filled="false"
                                name="weight"
                                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" 
                                />
                            </div>
                            <Custominput
                                label="Precio*"
                                type="Number"
                                :filled="false"
                                name="price"
                                v-model:field="formLoad.price"
                            />
                            <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"
                            />
                            <Custominput
                                label="Dirección*"
                                type="text"
                                :filled="false"
                                name="address-origin"
                                v-model:field="origin.address"
                            />
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Ciudad*</label>
                                <Cities
                                    v-model="origin.city" 
                                />
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Estado*</label>
                                <States
                                    v-model="origin.state" 
                                />
                            </div>
                            <Custominput
                                label="País*"
                                type="text"
                                :filled="false"
                                name="country-origin"
                                v-model:field="origin.country"
                            />
                            <Custominput
                                label="Código Postal*"
                                type="text"
                                :filled="false"
                                name="postalCode-origin"
                                v-model:field="origin.postalCode"
                            />
                            <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"
                            />
                            <Custominput
                                label="Dirección"
                                type="text"
                                :filled="false"
                                name="address-destination"
                                v-model:field="destination.address"
                            />
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Ciudad*</label>
                                <Cities
                                    v-model="destination.city" 
                                />
                            </div>
                            <div class="mb-4 mt-3">
                                <label class="custom-label">Estado*</label>
                                <States
                                    v-model="destination.state" 
                                />
                            </div>
                            <Custominput
                                label="País*"
                                type="text"
                                :filled="false"
                                name="country-destination"
                                v-model:field="destination.country"
                            />
                            <Custominput
                                label="Código Postal*"
                                type="text"
                                :filled="false"
                                name="postalCode-destination"
                                v-model:field="destination.postalCode"
                            />
                            <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="button" 
                        class="btn-primary-sm radius-sm" 
                        @click=""
                    >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;
    }

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