<script setup>
    import { onMounted, ref, watch } from 'vue';
    import { useCompanyStore } from '../stores/company';
    import Spiner from '../components/ui/Spiner.vue';
    import CardEmpty from '../components/CardEmpty.vue';
    import CreateLocationModal from '../components/CreateLocationModal.vue';
    import CardLocation from '../components/CardLocation.vue';
    import Pagination from '../components/Pagination.vue';
    import CustomPopup from '../components/CustomPopup.vue';
    import { useI18n } from 'vue-i18n';

    const companyStore = useCompanyStore();

    const loading = ref(false);
    const filterQuery = ref([]);
    const query = ref('');
    const locationCurrent = ref(null);
    const openModal = ref(false);
    const { t, locale } = useI18n();
    // const typeDirection = ref(null)
    const typeDirection = ref({value: 'both', label: t('labels.both')})
    const optionsFilter = ref([]);
    const openPopup = ref(false);


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

    const limit = 10;

    const getInitData = async() => {
        loading.value = true;
        // companyStore.locationsCurrentPage = companyStore.locationsCurrentPage;
        filterQuery.value.company = "company="+ localStorage.getItem('id');
        filterQuery.value.limit = "elements=" + limit;
        filterQuery.value.page = "page=" + 0;
        await companyStore.getLocationsCompany(filterQuery.value, false)
        optionsFilter.value = [
            {value: 'both',label: t('labels.both')},
            {value: 'load',label: t('labels.load')},
            {value: 'download',label: t('labels.download')}
        ]
        loading.value = false;
    }

    watch(locale, () => {
        optionsFilter.value = [
            {value: 'both',label: t('labels.both')},
            {value: 'load',label: t('labels.load')},
            {value: 'download',label: t('labels.download')}
        ]
    })

    const getLocationsByPage = async(data) => {
        loading.value = true;
        filterQuery.value.company = "company="+ localStorage.getItem('id');
        filterQuery.value.page = "page=" + data.page;
        companyStore.locationsCurrentPage = data.page
        await companyStore.getLocationsCompany(filterQuery.value, true)
        loading.value = false;
    }

    const getLocationsWithFilters = async(filter) => {
        loading.value = true;
        await companyStore.getLocationsCompany(filter, true);
        loading.value = false;
    }

    watch(query, () => {
        filterQuery.value.page = "page=" + 0;
        filterQuery.value.limit = "elements=" + 100;
        if(query.value.length === 0){
            clearRequest();
            filterQuery.value.search = "";
            // filterQuery.value.page = 1
            getLocationsWithFilters(filterQuery.value);
        }
    });

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

    const clearFilter = () => {
        clearRequest();

        filterQuery.value.search = "";
        filterQuery.value.company = "company="+ localStorage.getItem('id');
        if(query.value == ''){
            getInitData();
        } else {
            query.value = '';
        }
    }

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

    const handleSetCurrentLocation = (location) => {
        openModal.value = true;
        locationCurrent.value = location;
    }

    const handleResetCurrentBudget = () => {
        openModal.value = false;
        locationCurrent.value = null;
    }

    const selectedType = (type) => {
        console.log(type)
        typeDirection.value = type
        openPopup.value = false
    }

    const closePopup = () => {
        openPopup.value = false
    }

</script>

<template>
    <div
        v-if="openPopup"
    >
        <CustomPopup 
            :options="optionsFilter" 
            :value="typeDirection" 
            @change-value="selectedType"
            @close-popup="closePopup"
            selected-color="#e3a11e"
        />
    </div>
    <div>
        <CreateLocationModal 
            v-if="openModal === true"
            :location="locationCurrent"
            @reset-location="handleResetCurrentBudget"
        />
        <h2 class="title">{{ t('global.directory') }}</h2>
        <div class="box-filters">
            <div class="box-search">
                <input class="form-control custom-search" type="search" name="" :placeholder="t('directory.querySearch')" id="" @:input="search()" v-model="query" aria-label="Search">
            </div>
            <div class="box-directory"
                @click="openPopup = true"
            >
                <span class="clear-sm" v-if="typeDirection === null">{{ t('directory.directory') }}</span>
                <span class="clear-sm" v-else>{{typeDirection.label}}</span>
                <i class="fa-solid fa-filter"></i>
            </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"> {{ t('labels.filters').toLocaleLowerCase() }}</span>
            </button>
            <button
                class="btn-primary-sm radius-sm"
                data-toggle="modal" data-target="#locationFormModal"
                @click="handleSetCurrentLocation(null)"
            ><i class="fa-solid fa-plus"></i> <span class="clear-sm"> {{ t('buttons.add') }}</span> <span class="clear-md"> {{ t('labels.location') }}</span></button>
        </div>
        <div v-if="loading" class="spiner-box">
            <Spiner/>
        </div>
        <div v-else>
            <CardLocation
                v-if="companyStore.locations.length > 0"
                v-for="location in companyStore.locations"
                :key="location._id"
                :location="location" 
                @set-location="handleSetCurrentLocation(location)"
            />
            <CardEmpty v-else :text="t('directory.msgEmpty')"/>
            <Pagination
                :limit="limit"
                :total="companyStore.locationsTotal"
                :current-page="companyStore.locationsCurrentPage"
                @get-elements="getLocationsByPage"
            />
        </div>
    </div>
</template>

<style lang="scss" scoped>
    .box-filters {
        display: flex;
        flex-direction: row;
        justify-content: end;
        gap: 1rem;
        margin: 1.5rem 0px;
    }
    .box-filter-location {
        background-color: white;
    }

    .section-h4 {
        font-size: 1rem;
    }

    .box-custom {
        background-color: red!important;
        width: 100px;
    }

    .box-directory {
        padding: 12px 8px;
        background-color: #FFF;
        border-radius: 5px;
        display: flex;
        flex-direction: row;
        border: 1px rgb(186, 175, 175) solid;
        gap: 1rem;
        align-items: center;
        cursor: pointer;
    }

    .box-search {
        // width: 50%;
        flex: 1;
    }
    .custom-search {
        width: 100%;
        padding: 12px 20px;
    }


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

    @media (max-width: 768px) {

        .box-search {
            width: 100%;
        }
        .box-filters {
            gap: .3rem;
        }
    }
</style>