<script setup>
    import { onMounted, ref, watch } from 'vue';
    import Spiner from '../components/ui/Spiner.vue';
    import CardLoad from '../components/CardLoad.vue';
    import AttachmentsModal from '../components/AttachmentsModal.vue';
    import { useLoadsStore } from '../stores/loads';
    import FormLoadModal from '../components/FormLoadModal.vue';
    import ProposalsModal from '../components/ProposalsModal.vue';
    import CardEmpty from '../components/CardEmpty.vue';
    import Pagination from '../components/Pagination.vue';

    const loadStore = useLoadsStore();
    const loading = ref(false);
    const query = ref('');
    const filterQuery = ref([]);
    const limit = 3;

    onMounted(() =>{
        console.log('init')
        getDataLoadsInit(false);
    })

    ///loads?company=64fa70c130d2650011ac4f3a&$limit=3&$skip=0&status[$ne]=Closed&$sort%5BcreatedAt%5D=-1

    watch(query, () => {
        filterQuery.value.skip = "$skip="+ 0;
        filterQuery.value.limit = "$limit="+ 100;
        if(query.value.length === 0){
            console.log('Clear manueal')
            // console.log(loadStore.loadsTotal)
            clearRequest();
            filterQuery.value.search = "";
            getLoadWithFilters(filterQuery.value);
        }
    });

    const getDataLoadsInit = async(reload) => {
        filterQuery.value.limit = '$limit=' + limit;
        filterQuery.value.skip = "$skip=0"
        filterQuery.value.status = "status[$ne]="+"Closed";
        loading.value = true;
        await loadStore.getCompanyLoads(filterQuery.value, reload);
        loading.value = false;
    }

    const getLoadsByPage = async(data) => {
        console.log(data);
        loading.value = true;
        filterQuery.value.skip = "$skip="+ data.skip;
        loadStore.loadsCurrentPage = data.page
        await loadStore.getCompanyLoads(filterQuery.value, true)
        loading.value = false;
    }
    
    const getLoadWithFilters = async(filter) => {
        loading.value = true;
        await loadStore.getCompanyLoads(filter, true);
        loading.value = false;
    }

    const search = () => {
        setTimeout(() => {
            if(query.value.length >= 2){
                // filterQuery.value = "company_name[$regex]=" + query.value + "&company_name[$options]=i";
                filterQuery.value.search = "posted_by_name[$regex]="+query.value+"&posted_by_name[$options]=i";
                getLoadWithFilters(filterQuery.value);
            } 
        }, 100)
    
    }

    const clearFilter = () => {
        clearRequest();
        filterQuery.value.search = ""
        filterQuery.value.status = "status[$ne]="+"Closed";
        console.log('click here');
        if(query.value == ''){
            getDataLoadsInit(true);
        } else {
            query.value = '';
        }
    }

    const clearRequest = () => {
        filterQuery.value.skip = "$skip="+ 0;
        filterQuery.value.limit = "$limit="+ limit;
        loadStore.loadsCurrentPage = 1;
    }

    const loadHistory = () => {
        clearRequest();
        filterQuery.value.status = ""
        filterQuery.value.status = "status="+ "Closed";
        getLoadWithFilters(filterQuery.value);
    }
</script>

<template>
    <AttachmentsModal v-if="loadStore.openAttachmentsModal"/>
    <FormLoadModal v-if="loadStore.openModalEdit"/>
    <ProposalsModal v-if="loadStore.openProposalsModal"/>
    <div>
        <h2 class="title mb-5">Mis cargas publicadas</h2>
        <div>
            <div class="box-filters">
                <div class="box-search">
                    <input class="form-control custom-search" type="search" name="" placeholder="Nombre de la persona que publica" id="" @:input="search()" v-model="query" aria-label="Search">
                </div>
                <button 
                    class="btn btn-danger bg-dark" type="button" @click="clearFilter">
                    <i class="fa-solid fa-arrow-rotate-right"></i>
                    <span class="clear-sm"> Reset</span><span class="clear-md"> filtros</span>
                </button>
                <button
                    @click="loadHistory"
                    class="btn-primary-sm radius-sm"
                ><i class="fa-solid fa-clock-rotate-left"></i><span class="clear-sm"> Historial</span><span class="clear-md"> de cargas</span></button>
                <button
                    class="btn-primary-sm radius-sm"
                    data-toggle="modal" data-target="#formLoadModal"
                    @click="loadStore.openModalEdit = true"
                ><i class="fa-solid fa-plus"></i> <span class="clear-sm"> Crear</span><span class="clear-md"> carga</span></button>
            </div>
            <Spiner v-if="loading"/>
            <div v-else>
                <CardLoad 
                    v-if="loadStore.loads.length > 0"
                    v-for="load in loadStore.loads"
                    :key="load._id"
                    :load="load" 
                />
                <CardEmpty v-else text="No hay cargas agregadas"/>
                <Pagination
                    :limit="limit"
                    :total="loadStore.loadsTotal"
                    :current-page="loadStore.loadsCurrentPage"
                    @get-elements="getLoadsByPage"
                />
            </div>
        </div>
    </div>
</template>

<style scoped>
    .box-filters {
        display: flex;
        flex-direction: row;
        justify-content: end;
        gap: 1rem;
    }

    .box-search {
        width: 40%;
    }

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

    .custom-search {
        width: 100%;
        padding: 12px 20px;
    }

    @media (max-width: 1024px) {
        .box-search {
            width: 50%;
        }
        .box-filters {
            gap: .4rem;
        }
    }

    @media (max-width: 768px) {

        .box-search {
            width: 100%;
        }
        .box-filters {
            gap: .3rem;
        }
    }

</style>