<script setup>
    import { getDateOnly } from '../helpers/date_formats';
    import { getStatusPublished } from '../helpers/status';
    import { getStatusLoad } from '../helpers/status';
    import { useLoadsStore } from '../stores/loads';
    import Swal from 'sweetalert2'
    import { useAuthStore } from '../stores/auth';
    import { useI18n } from 'vue-i18n';

    const loadsStore = useLoadsStore();
    const authStore = useAuthStore();

    const props = defineProps({
        load: {
            type: Object,
            required: true,
        },
        readOnly: {
            type: Boolean,
            required: false,
            default: false
        },
        tracking: {
            type: Boolean,
            required: false,
            default: true
        },
        share: {
            type: Boolean,
            required: false,
            default: false
        }
    });

    const { t } = useI18n()
    defineEmits(['set-load'])

    const openAttachmentsModal = () => {
        loadsStore.currentLoad = props.load;
        loadsStore.openAttachmentsModal = true;
    }

    const handleDeleteLoad = async() => {
        Swal.fire({
            title: t('loads.titleDel'),
            text: t('loads.textDel'),
            icon: 'warning',
            showCancelButton: true,
            cancelButtonColor: "#d33",
            confirmButtonText: t('buttons.delete'),
            cancelButtonText: t('buttons.cancel'),
        }).then(async(result) => {
            if(result.isConfirmed) {
                Swal.fire({
                    title: t('messages.loading'),
                    html: t('loads.loadingDel') + '...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading()
                    },
                });
                const resp = await loadsStore.deleteLoad(props.load._id);
                if(resp != null) {
                    loadsStore.loads = loadsStore.loads.filter(load => load._id !== props.load._id);
                    Swal.fire({
                        title: t('loads.msgTitleDel'),
                        text: t('loads.msgDel'),
                        icon: "success"
                    });
                } else {
                    Swal.fire({
                        title: t('errors.msgTitleNotDel'),
                        text: t('loads.msgNotDel'),
                        icon: "error"
                    });
                }
            }

        });

    }

    const openEditModal = () => {
        loadsStore.currentLoad = props.load
        loadsStore.openModalEdit = true;
    }

    const openProposalsModal = () => {
        loadsStore.currentLoad = props.load
        loadsStore.openProposalsModal = true;
    }

    const openCarrierInfoModal = () => {
        loadsStore.currentLoad = props.load
        loadsStore.openCarrierInfoModal = true;
    }

    const handleTracking = () => {
        let code = props.load._id;
        window.open('/publico/tracking/' + code, '_blank');
    }

    const sharePost = () => {
        const url = `https://console.etaviaporte.com/publico/carga/${props.load._id}`;
        const title = "Revisa mi publicación de carga, ¡podría interesarte!";
        
        navigator.share({
          title: title,
          url: url,
        })
        .then(() => {
          console.log("Enlace compartido con éxito");
        })
        .catch((error) => {
          console.log('Usuario cancelo')
        });
    }

</script>

<template>
    <div class="card-fixed card-load mt-4">
        <div class="row">
            <div class="col-lg-6 col-sm-12">
                <p>
                    <span>{{t('loads.origin')}}: </span> 
                    <template v-if="load.origin?.company_name"> {{ load.origin?.company_name }}, </template> 
                    <template v-if="load.origin?.street_address1">{{ load.origin?.street_address1 }}, </template>
                    <template v-if="load.origin?.city">{{ load.origin?.city }}, </template>
                    <template v-if="load.origin?.state">{{ load.origin?.state }}, </template>
                    <template v-if="load.origin?.country">{{ load.origin?.country }}, </template>
                    <template v-if="load.origin?.zipcode">{{ load.origin?.zipcode }} </template>
                </p>
                <p>
                    <span>{{t('loads.destination')}}: </span> 
                    <template v-if="load.destination?.company_name"> {{ load.destination?.company_name }}, </template> 
                    <template v-if="load.destination?.street_address1">{{ load.destination?.street_address1 }}, </template>
                    <template v-if="load.destination?.city">{{ load.destination?.city }}, </template>
                    <template v-if="load.destination?.state">{{ load.destination?.state }}, </template>
                    <template v-if="load.destination?.country">{{ load.destination?.country }}, </template>
                    <template v-if="load.destination?.zipcode">{{ load.destination?.zipcode }} </template>
                </p>
            </div>
            <div class="col-lg-6 col-sm-12">
                <p v-if="readOnly">
                    <span>{{t('loads.company')}}: </span> 
                    {{ load.company?.company_name }} 
                </p>
                <div v-if="!readOnly">
                    <p>
                        <span>{{t('loads.postStatus')}}: </span> 
                        <span class="simple"> {{ getStatusPublished(load) }}</span>
                        <i 
                            v-if="load.status !== 'Draft' && load.status !== 'Published'"
                            class="fa-solid fa-truck me-1 ms-1 pointer" 
                            data-toggle="modal" 
                            data-target="#carrierInfoModal"
                            @click="openCarrierInfoModal()"
                            style="color: green; font-size: 20px;"
                        ></i>
                    </p>
                    <p :style="{color: getStatusLoad(load).color}"><span>{{t('loads.loadStatus')}}:</span> <span class="simple">{{ getStatusLoad(load).status }}</span></p>
                </div>
            </div>
        </div>
        <div class="divider"></div>
        <br>
        <div class="row">
            <div class="col-lg-4 col-sm-12">
                <p><span>{{t('loads.truckType')}}: </span> {{ load.truck_type }}</p>
                <p><span>{{t('loads.weight')}}: </span> {{ load.weight }} KG</p>
                <p><span>{{t('loads.dateLoad')}}: </span> {{ getDateOnly(load.est_loading_date) }}</p>
            </div>
            <div class="col-lg-4 col-sm-12">
                <p><span>{{t('loads.product')}}: </span> {{ load?.product?.name }}</p>
                <p><span>{{t('loads.cost')}}: </span> {{ load.actual_cost }}</p>
                <p><span>{{t('loads.dateDownload')}}: </span> {{getDateOnly(load.est_unloading_date)  }}</p>
            </div>
            <div class="col-lg-4 col-sm-12">
                <p><span>{{t('global.segment')}}: </span> {{ load.categories?.map((e) => e.name).join(', ') }}</p>
                <p><span>{{t('loads.loadCode')}}: </span> {{ load.shipment_code?.toUpperCase() }}
                    <span 
                        v-if="load.status !== 'Draft' && tracking" 
                        class="tracking-icon" 
                        @click="handleTracking" 
                        data-target="_blank"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg"  fill="currentColor" class="bi bi-geo-alt-fill" viewBox="0 0 16 16">
                        <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10zm0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"></path>
                        </svg>
                    </span>
                </p>
                <p><span>{{t('loads.postBy')}}: </span> {{ load.posted_by_name }}</p>
            </div>
        </div>
        <p v-if="load.notes"><span>{{ t('loads.note') }}:</span></p>
        <div v-if="load.notes" class="box-note">
            {{ load.notes }}
        </div>
        <div class="btn-row">
            <button  v-if="load.status !== 'Draft' && load.load_status !== 'Published' && load.load_status !== 'Loading' && !tracking && !share" 
                type="button" 
                 data-toggle="modal" data-target="#attachmentModal" 
                class="btn-primary-sm" 
                @click="openAttachmentsModal"
            >
                <i class="fa-solid fa-image"></i>
                {{ t('evidence.evidence') }}
            </button>
        </div>
        <div class="btn-row" v-if="load?.company?._id === authStore?.user?.company._id && !share">
            <button  v-if="load.status !== 'Draft' && load.load_status !== 'Delivered'" 
                type="button" 
                class="btn-primary-sm" 
                @click="sharePost"
            >
                <i class="fa-solid fa-share-nodes"></i>
                <span class="clear-sm ms-1">{{t('buttons.share')}}</span>
            </button>
            <button  v-if="load.status !== 'Draft' && load.load_status !== 'Published' && load.load_status !== 'Loading'" 
                type="button" 
                 data-toggle="modal" data-target="#attachmentModal" 
                class="btn-primary-sm" 
                @click="openAttachmentsModal"
            >
                <i class="fa-solid fa-image"></i>
                <span class="clear-sm ms-1">{{ t('evidence.evidence') }}</span> 
            </button>
            <button
                v-if="(authStore.user?.job_role === 'owner' || authStore.user?.job_role === 'manager') || authStore.user._id === props.load.posted_by"
                class="btn-primary-sm bg-danger"
                @click="handleDeleteLoad"
            >
                <i class="fa-solid fa-trash"></i> 
                <span class="clear-sm ms-1">{{ t('buttons.cancel') }}</span>
            </button>
            <button
                v-if="(authStore.user?.job_role === 'owner' || authStore.user?.job_role === 'manager') || authStore.user._id === props.load.posted_by"
                class="btn-primary-sm bg-dark"
                data-toggle="modal" data-target="#formLoadModal"
                @click="openEditModal"
            >
                <i class="fa-solid fa-pen-to-square"></i> 
                <span class="clear-sm ms-1">{{t('loads.editLoad')}}</span>
            </button>
            <button
                v-if="load.status !== 'Draft'"
                class="btn-primary-sm"
                @click="openProposalsModal"
                data-toggle="modal" 
                data-target="#proposalsModal"
            >#{{ load.no_of_proposals }} {{t('loads.offers')}}</button>
        </div>
        <div class="btn-row" v-if="readOnly && authStore.user?.permissions === 'role_carrier' || share">
            <button
                class="btn-primary-sm bg-dark"
                data-toggle="modal" 
                data-target="#makeProposalModal"
                @click="event => $emit('set-load')"
            >{{t('loads.makeOffer')}}</button>
        </div>
    </div>
</template>

<style  scoped>
    .card-load {
        flex-direction: column;
        width: 100% !important;
    }

    .tracking-icon {
        cursor: pointer;
        color: #f2a23f;
    }

    .tracking-icon svg{
    height: 30px;
    }
    .tracking-icon:hover {
        color: #ddb380;;
        height: 150px;
    }

    .tracking-icon svg:hover{
        height: 33px;
    }

    p .simple {
        font-size: 1rem;
        font-weight: 400;
        color: #323032;
    }
    
    p span {
        color: #323032;
        font-weight: 700;
    }

    
    .btn-row {
        margin-top: 2rem;
        display: flex;
        flex-direction: row;
        justify-content: end;
        gap: 1rem;
    }

    .box-note {
        padding: 12px 16px;
        background-color: aqua;
        border-radius: 13px;
    }
    
    @media (max-width: 768px) {
        .btn-row {
            gap: 0.2rem;
        }
    }
</style>