<script setup>
    import { useRouter } from 'vue-router';
    import { getDateMonthDay } from '../helpers/date_formats';
    import { getStatusPublished } from '../helpers/status';
    import { getStatusLoad } from '../helpers/status';
    import { useLoadsStore } from '../stores/loads';
    import Swal from 'sweetalert2'

    const router = useRouter();
    const loadsStore = useLoadsStore();

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



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

    const handleDeleteLoad = async() => {
        Swal.fire({
            title: 'Eliminar carga!',
            text: '¿Estás seguro de eliminar esta carga?',
            icon: 'warning',
            showCancelButton: true,
            cancelButtonColor: "#d33",
            confirmButtonText: 'Eliminar',
            cancelButtonText: 'Cancelar',
        }).then(async(result) => {
            if(result.isConfirmed) {
                Swal.fire({
                    title: 'Por favor espere!',
                    html: 'Eliminando carga...',// add html attribute if you want or remove
                    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: "Carga eliminada!",
                        text: "Tu carga ha sido eliminada exitosamente.",
                        icon: "success"
                    });
                } else {
                    Swal.fire({
                        title: "No eliminado!",
                        text: "Tu carga no se pudo eliminar, intente más tarde.",
                        icon: "error"
                    });
                }
            }

        });

    }

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

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

    const handleTracking = () => {
        let code = props.load.shipment_code;
		router.push({
            name: 'tracking-load',
            params: {code}
        });
    }

</script>

<template>
    <div class="card-fixed card-load mt-4">
        <div class="row">
            <div class="col-lg-6 col-sm-12">
                <p><span>Origen:</span> {{ load.origin.company_name }}, {{ load.origin_formatted_address }}</p>
                <p><span>Destino:</span> {{ load.destination.company_name }}, {{ load.destination_formatted_address }}</p>
            </div>
            <div class="col-lg-6 col-sm-12">
                <p><span>Status de la publicación:</span> <span>{{ getStatusPublished(load) }}</span></p>
                <p :style="{color: getStatusLoad(load).color}"><span>Status de la carga:</span> <span>{{ getStatusLoad(load).status }}</span></p>
            </div>
        </div>
        <div class="divider"></div>
        <br>
        <div class="row">
            <div class="col-lg-4 col-sm-12">
                <p><span>Tipo de camión: </span> {{ load.truck_type }}</p>
                <p><span>Peso: </span> {{ load.weight }} KG</p>
                <p><span>Fecha de carga: </span> {{ getDateMonthDay(load.est_loading_date) }}</p>
            </div>
            <div class="col-lg-4 col-sm-12">
                <p><span>Producto: </span> {{ load?.product?.name }}</p>
                <p><span>Costo real: </span> {{ load.actual_cost }}</p>
                <p><span>Fecha de descarga: </span> {{getDateMonthDay(load.est_unloading_date)  }}</p>
            </div>
            <div class="col-lg-4 col-sm-12">
                <p><span>Segmento: </span> {{ load._categories }}</p>
                <p><span>Código de carga: </span> {{ load.shipment_code }}
                    <span v-if="load.load_status !== 'Draft' && !readOnly" class="tracking-icon" @click="handleTracking">
                        <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>Publicación hecha por: </span> {{ load.posted_by_name }}</p>
            </div>
        </div>
        <p v-if="load.notes"><span>Notas adicionales:</span></p>
        <div v-if="load.notes" class="box-note">
            {{ load.notes }}
        </div>
        <div class="btn-row" v-if="!readOnly">
            <button
                class="btn-primary-sm bg-dark"
                @click="handleDeleteLoad"
            ><i class="fa-solid fa-ban clear-sm"></i> Cancelar</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>
                Evidencias
            </button>
            <button
                v-if="load.load_status !== 'Delivered'"
                class="btn-primary-sm"
                data-toggle="modal" data-target="#formLoadModal"
                @click="openEditModal"
            ><i class="fa-solid fa-pen-to-square clear-sm"></i> Editar carga</button>
            <button
                v-if="load.status !== 'Draft'"
                class="btn-primary-sm"
                @click="openProposalsModal"
                data-toggle="modal" 
                data-target="#proposalsModal"
            >#{{ load.no_of_proposals }} Ofertas</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 {
        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>