<script setup>
import { onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useArrayData } from 'composables/useArrayData';

const props = defineProps({
    dataKey: {
        type: String,
        required: true,
    },
    label: {
        type: String,
        required: false,
        default: 'Search',
    },
    info: {
        type: String,
        required: false,
        default: '',
    },
    redirect: {
        type: Boolean,
        required: false,
        default: true,
    },
});

const router = useRouter();
const route = useRoute();
const arrayData = useArrayData(props.dataKey);
const store = arrayData.store;
const searchText = ref('');

onMounted(() => {
    const params = store.userParams;
    if (params && params.search) {
        searchText.value = params.search;
    }
});

async function search() {
    await arrayData.applyFilter({
        params: {
            search: searchText.value,
        },
    });
    if (!props.redirect) return;

    const rows = store.data;
    const module = route.matched[1];
    if (rows.length === 1) {
        const [firstRow] = rows;
        await router.push({ path: `/${module.name}/${firstRow.id}` });
    } else if (route.matched.length > 3) {
        await router.push({ path: `/${module.name}` });
        arrayData.updateStateParams();
    }
}
</script>

<template>
    <q-form @submit="search">
        <q-input
            id="searchbar"
            v-model="searchText"
            :placeholder="props.label"
            dense
            standout
            autofocus
        >
            <template #prepend>
                <q-icon name="search" />
            </template>
            <template #append>
                <q-icon
                    v-if="searchText !== ''"
                    name="close"
                    @click="searchText = ''"
                    class="cursor-pointer"
                />

                <q-icon v-if="props.info" name="info" class="cursor-info">
                    <q-tooltip>{{ props.info }}</q-tooltip>
                </q-icon>
            </template>
        </q-input>
    </q-form>
</template>

<style lang="scss" scoped>
@media screen and (max-width: $breakpoint-xs-max) {
    .q-field {
        width: 250px;
    }
}

@media screen and (min-width: $breakpoint-xs-max) {
    .q-field {
        width: 400px;
    }
}

.q-field {
    transition: width 0.36s;
}
</style>

<style lang="scss">
.cursor-info {
    cursor: help;
}

.body--light #searchbar {
    .q-field--standout.q-field--highlighted .q-field__control {
        background-color: $grey-7;
        color: #333;
    }
}
</style>
