<script setup>
    import { onMounted, ref, watch } from 'vue';
    import useSearchLoads from '../../composables/userSearchLoads';
    import Spiner from '../../components/ui/Spiner.vue';
    import CardLoad from '../../components/CardLoad.vue'
    import CardEmpty from '../../components/CardEmpty.vue'
    import TruckTypes from '../../components/ui/TruckTypes.vue';
    import Segments from '../../components/ui/Segments.vue';
    import States from '../../components/ui/States.vue';
    import Cities from '../../components/ui/Cities.vue';
    import MakeProposalModal from '../../components/MakeProposalModal.vue';
    import Pagination from '../../components/Pagination.vue';
    import { useI18n } from 'vue-i18n';

    const filterQuery = ref([]);
    const query = ref('');
    const selectedTruckType = ref([]);
    const selectedCategory = ref([]);
    const selectedState = ref([]);
    const selectedCities = ref([]);
    const limit = 10;
    const isSearch = ref(false);
    const { getLoadsPublished, loads, loading, currentPage, total } = useSearchLoads();

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

    const { t } = useI18n()

    watch(query, () => {
        isSearch.value = true;
        setFilterUnlimited();
        if(query.value.length === 0){
            if(selectedCategory.value?.length === 0  && selectedTruckType.value?.length === 0 && selectedCities.value?.length === 0 && selectedState.value?.length === 0 ) {
                clearRequest();
                isSearch.value = false;
            }
            filterQuery.value.search = "";
            getLoadsPublished(filterQuery.value);
        }
    });

    watch(selectedState, () => {
        if(selectedState.value != null){
            setFilterUnlimited()
            filterQuery.value.state = "state="+ selectedState.value.state_name;
            getLoadsPublished(filterQuery.value);
        } 
    });

    watch(selectedCities, () => {
        if(selectedCities.value != null){
            setFilterUnlimited()
            filterQuery.value.city = "city="+ selectedCities.value.city_name;
            getLoadsPublished(filterQuery.value);
        } 
    });

    watch(selectedCategory, () => {
        if(selectedCategory.value != null){
            setFilterUnlimited()
            filterQuery.value.category = "categories=" + selectedCategory.value._id;
            getLoadsPublished(filterQuery.value);
        } 
    });

    watch(selectedTruckType, () => {
        if(selectedTruckType.value != null){
            setFilterUnlimited()
            filterQuery.value.truck_type = "truck_type="+ selectedTruckType.value.meta_value;
            getLoadsPublished(filterQuery.value);
        } 
    });

    const search = () => {
        if(query.value.length >= 2){
            filterQuery.value.search = "company_name[$regex]=" + query.value + "&company_name[$options]=i";
            // filterQuery.value.search = "company.company_name[$regex]=" + query.value + "&company.company_name[$options]=i";
            getLoadsPublished(filterQuery.value);
        } 
    
    }

    const clearFilter = () => {
        clearRequest();
        isSearch.value = false;
        selectedCities.value = null;
        selectedCategory.value = null;
        selectedState.value = null;
        selectedTruckType.value = null;

        filterQuery.value.truck_type = "";
        filterQuery.value.category = "";
        filterQuery.value.city = "";
        filterQuery.value.state = "";

        filterQuery.value.status = "status=Published";

        if(query.value == ''){
            getLoadsPublished(filterQuery.value);
        } else {
            query.value = '';
        }
    }

    const clearState = () => {
        filterQuery.value.state = "";
        getLoadsPublished(filterQuery.value);
    }

    const clearCity = () => {
        filterQuery.value.city = "";
        getLoadsPublished(filterQuery.value);
    }

    const clearTruckType = () => {
        filterQuery.value.truck_type = "";
        getLoadsPublished(filterQuery.value);
    }

    const clearCategory = () => {
        filterQuery.value.category = "";
        getLoadsPublished(filterQuery.value);
    }

    const getInitData = async() => {
        filterQuery.value.limit = 'elements=' + limit;
        filterQuery.value.page = "page=0";
        filterQuery.value.company = "";

        filterQuery.value.status = "status=Published",
        await getLoadsPublished(filterQuery.value);
    }

    const getLoadsByPage = (data) => {
        filterQuery.value.page = "page="+ data.page;
        currentPage.value = data.page
        getLoadsPublished(filterQuery.value);
    }

    const clearRequest = () => {
        filterQuery.value.page = "page="+ 0;
        filterQuery.value.limit = "elements="+ limit;
        currentPage.value = 0;
    }

    const setFilterUnlimited = () => {
        filterQuery.value.page = "page="+ 0;
        filterQuery.value.limit = "elements="+ 100;
    }

    const currentLoad = ref(null);

    const handleSetCurrentLoad = (load) => {
        currentLoad.value = load
    }

    const handleResetCurrentLoad = () => {
        currentLoad.value = null
    }

    const removeLoadOfList = (load) => {
        loads.value = loads.value.filter((e) => e._id !== load._id);
    }
</script>

<template>
    <h2 class="title mb-5">{{ t('loads.searchLoads') }}</h2>
    <MakeProposalModal 
        v-if="currentLoad" 
        :load="currentLoad"
        @reset-load="handleResetCurrentLoad"
        @remove-load="removeLoadOfList"
    />

    <div class="card-filters">
        <div class="d-flex mb-2">
            <input class="form-control me-2" type="search" name="" :placeholder="t('shippers.searchShipper')" id="" @:input="search()" v-model="query" aria-label="Search">
            <button class="btn btn-outline-dark me-2" type="button" @click="search">{{ t('buttons.search') }}</button>
            <button 
                class="btn btn-danger" type="button" @click="clearFilter">
                <i class="fa-solid fa-arrow-rotate-right"></i>
            </button>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-6 px-2 py-2">
                <TruckTypes v-model="selectedTruckType" @clear-option="clearTruckType"/>
            </div>
            <div class=" col-xs-12 col-sm-6 px-2 py-2">
                <Segments v-model="selectedCategory" @clear-option="clearCategory"/>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-6 px-2 py-2">
                <States v-model="selectedState" @clear-option="clearState"/>
            </div>
            <div class="col-xs-12 col-sm-6 px-2 py-2">
                <Cities v-model="selectedCities" @clear-option="clearCity"/>
            </div>
        </div>
    </div>
    <Spiner class="mt-4" v-if="loading"/>
    <div v-else>
        <CardLoad 
            v-if="loads.length > 0" 
            v-for="load in loads"
            :load="load"
            :read-only="true"
            @set-load="handleSetCurrentLoad(load)"
        />
        <CardEmpty 
            v-else
            text="No hay cargas publicadas"
        />
        <Pagination
            v-if="!isSearch"
            :limit="limit"
            :total="total"
            :current-page="currentPage"
            @get-elements="getLoadsByPage"
        />
    </div>
</template>

<style scoped>
    .card-filters {
        display: flex;
        margin: 0 auto;
        background-color: #FFF;
        border-radius: 13px;
        /* background-color: red; */
        flex-direction: column;
        /* align-items: center; */
        justify-content: center;
        width: 100%;
        padding: 20px 10%;
        margin-bottom: 24px;
    }

    @media (max-width: 768px) {
        .card-filters {
            padding: 20px 16px;
        }
    }
</style>