<script setup>
import { onMounted, ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import VnInput from 'src/components/common/VnInput.vue';

const props = defineProps({
    searchFn: {
        type: Function,
        default: null
    },
    placeholder: {
        type: String,
        default: ''
    },
    sqlQuery: {
        type: String,
        default: null
    },
    searchField: {
        type: String,
        default: 'search'
    }
});

const emit = defineEmits(['onSearch', 'onSearchError']);

const jApi = inject('jApi');
const { t } = useI18n();
const router = useRouter();
const route = useRoute();

const searchTerm = ref('');

const search = async () => {
    try {
        let data = null;
        router.replace({
            query: searchTerm.value ? { search: searchTerm.value } : {}
        });

        if (!searchTerm.value) {
            emit('onSearchError');
            return;
        }

        if (props.sqlQuery) {
            data = await jApi.query(props.sqlQuery, {
                [props.searchField]: searchTerm.value
            });
        } else if (props.searchFn) {
            data = props.searchFn(searchTerm.value);
        }

        emit('onSearch', data);
    } catch (error) {
        console.error('Error searching:', error);
        emit('onSearchError');
    }
};

onMounted(() => {
    if (route.query.search) {
        searchTerm.value = route.query.search;
        search();
    }
});
</script>
<template>
    <VnInput
        v-model="searchTerm"
        @keyup.enter="search()"
        :placeholder="props.placeholder || t('search')"
        bg-color="white"
        is-outlined
        :clearable="false"
        class="searchbar"
        data-cy="searchBar"
    >
        <template #prepend>
            <QIcon name="search" class="cursor-pointer" @click="search()" />
        </template>
    </VnInput>
</template>

<style lang="scss" scoped>
@import 'src/css/responsive';

.searchbar {
    @include mobile {
        max-width: 120px;
    }
}
</style>
<i18n lang="yaml">
en-US:
    search: Search
es-ES:
    search: Buscar
ca-ES:
    search: Cercar
fr-FR:
    search: Rechercher
pt-PT:
    search: Pesquisar
</i18n>
