<script setup>
    import { onMounted, ref } from 'vue';
    import { useLoadsStore } from '../stores/loads';
    import { useAuthStore } from '../stores/auth';
    import Spiner from './ui/Spiner.vue';
    import { getDateMonthDay } from '../helpers/date_formats';
    import VehicleInfo from './VehicleInfo.vue';
    import Swal from 'sweetalert2'
import CardEmpty from './CardEmpty.vue';

    const loadsStore = useLoadsStore();
    const authStore = useAuthStore();
    const isLoading = ref(false);
    const isLoadingActions = ref(false);

    onMounted(() => {
        getProposalsData()
    });

    const getProposalsData = async() => {
        isLoading.value = true;
        await loadsStore.getProposalsOfLoads(loadsStore.currentLoad._id);
        isLoading.value = false;
    }

    const clearMoal = () => {
        loadsStore.openProposalsModal = false;
        loadsStore.currentLoad = false; 
    }

    const handleAceptedProposal = async(proposal) => {

        const load_id = proposal.load._id;

        let loadData = {
            status : "Completed",
            contract_start_date: new Date(),
            carrier: proposal.carrier._id,
            vehicle: proposal.vehicle._id,
        }

        isLoadingActions.value = true;
        let load = await loadsStore.updateLoad(load_id, loadData);

        if(load != null) {
            const index = loadsStore.loads.findIndex((load) => load._id === load_id);
            loadsStore.loads[index] = {
                ...loadsStore.loads[index],
                ...load
            };
            const proposal_id = proposal._id;
    
            let formData = {
                accepted_by : authStore.user,
                accepted_date : new Date(),
                is_accepted : true,
            }
            const resp = await loadsStore.updateProposal(proposal_id, formData);
            if(resp){
                const index = loadsStore.proposalsOfLoads.findIndex((p) => p._id === proposal_id);
                loadsStore.proposalsOfLoads[index] = {
                    ...proposal, 
                    ...formData
                };
                Swal.fire({
                    title: "Oferta aceptada!",
                    text: "La oferta fue aceptada exitosamente.",
                    icon: "success"
                });
            } else {
                Swal.fire({
                    title: "Error!",
                    text: "No se pudo actualizar oferta, intente más tarde.",
                    icon: "error"
                });
            }
        } else {
            Swal.fire({
                title: "Error!",
                text: "No se pudo aceptar oferta, intente más tarde.",
                icon: "error"
            });
        }
        isLoadingActions.value = false;

    }

    const handleCancelProposal = async(proposal) => { 
        const proposal_id = proposal._id;
        const load_id = proposal.load._id;
        const {isConfirmed} = await Swal.fire({
            title: 'Cancelar oferta!',
            text: '¿Estás seguro de cancelar esta oferta?',
            icon: 'warning',
            cancelButtonColor: "#d33",
            showCancelButton: true,
            confirmButtonText: 'Si, cancelar',
            cancelButtonText: 'No'
        })
        if( isConfirmed ) {
            let loadData = {
                status : "Published",
                contract_start_date: null,
                carrier: null,
                vehicle: null,
            }

            isLoadingActions.value = true;
            let load = await loadsStore.updateLoad(load_id, loadData);
            if(load) {
                const index = loadsStore.loads.findIndex((load) => load._id === load_id);
                loadsStore.loads[index] = {
                    ...loadsStore.loads[index],
                    ...load
                };
                let formData = {
                    accepted_by : null,
                    accepted_date : null,
                    is_accepted : false,
                }
                const resp = await loadsStore.updateProposal(proposal_id, formData);
                if(resp) {
                    const index = loadsStore.proposalsOfLoads.findIndex((p) => p._id === proposal._id);
                    loadsStore.proposalsOfLoads[index] = {
                        ...proposal, 
                        ...formData
                    };
                    Swal.fire({
                        title: "Oferta cancelada!",
                        text: "La oferta fue retirada exitosamente.",
                        icon: "success"
                    });
                } else {
                    Swal.fire({
                        title: "Error!",
                        text: "No se pudo retirar oferta, intente más tarde",
                        icon: "error"
                    });
                }
            } else {
                Swal.fire({
                    title: "Error!",
                    text: "Algo salio mal, intente más tarde",
                    icon: "error"
                });
            }
            isLoadingActions.value = false;
        } 
    }

</script>

<template>
   <div class="modal fade" id="proposalsModal" tabindex="-1" role="dialog" aria-labelledby="editcompany" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h2 class="title mt-2 mb-3">Ofertas</h2>
                <button 
                    id="btnCloseProposalsModal" 
                    type="button" 
                    @click="clearMoal"
                    class="close bg-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body view-proposals">
                <Spiner v-if="isLoading"/>
                <div v-else>
                    <div v-if="loadsStore.proposalsOfLoads.length > 0" v-for="proposal in loadsStore.proposalsOfLoads" class="card-fixed card-proposal">
                        <div class="row">
                            <div class="col-lg-6 col-md-12">
                                <p>Empresa: <span>{{ proposal.carrier.company_name }}</span></p>
                                <p>Licitador: <span>{{ proposal.bidder.first_name }} {{ proposal.bidder.last_name }}</span></p>
                                <p># de registro del transportista: <span v-if="proposal.vehicle">{{proposal.vehicle.vehicle_code}}</span></p>
                            </div>
                            <div class="col-lg-6 col-md-12">
                                <p>Fecha: <span>{{ getDateMonthDay(proposal.createdAt) }}</span></p>
                                <p>Tipo de Transporte: <span v-if="proposal.vehicle">{{proposal.vehicle.truck_type}}</span></p>
                                <p>Transportista: <span v-if="proposal._driver">{{proposal._driver}}</span></p>
                            </div>
                        </div>
                        <div v-if="proposal.comment" class="box-note">
                            {{ proposal.comment }}
                        </div>
                        <VehicleInfo v-if="proposal.vehicle" :vehicle="proposal.vehicle"/>
                        <Spiner v-if="isLoadingActions"/>
                        <div class="d-flex justify-content-end gap-3" v-else>
                            <div v-if="proposal.is_accepted" class="indicator-check">
                                <i class="fa-solid fa-check"></i>
                                Aceptado
                            </div>
                            <button  v-if="!proposal.is_accepted" 
                                type="button" 
                                class="btn-primary-sm" 
                                @click="handleAceptedProposal(proposal)"
                            >
                                <i class="fa-solid fa-check"></i>
                                Aceptar
                            </button>
                            <button
                                v-if="proposal.load.load_status !== 'Delivered' && proposal.is_accepted"
                                class="btn-primary-sm"
                                @click="handleCancelProposal(proposal)"
                                >
                                <i class="fa-solid fa-ban clear-sm"></i>
                                Cancelar
                            </button>
                        </div>
                    </div>
                    <CardEmpty v-else text="No hay ofertas"/>
                </div>
            </div>
            <div class="modal-footer">
                <button 
                    type="button" 
                    class="btn btn-dark" 
                    @click="clearMoal"
                    data-dismiss="modal">Cerrar</button>
            </div>
            </div>
        </div>
    </div>
</template>

<style scoped>

    .view-proposals {
        width: 100%;
    }

    .card-proposal {
        flex-direction: column;
        width: 100% !important;
    }

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

    .indicator-check {
        width: 120px;
        padding: 10px 12px;
        background: #FFF;
        border: 1px solid green;
        border-radius: 50px;
        color: green;
    }

    .box-note {
        padding: 12px 16px;
        background-color: aqua;
        border-radius: 13px;
    }
</style>