<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',
    },
    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 moduleRoute = route.matched[1];
    console.log(moduleRoute);

    const rows = store.data;
    if (rows.length === 1) {
        const firstRow = rows[0];
        const stateName = `${moduleRoute.name}Card`;
        await router.push({ name: stateName, params: { id: firstRow.id } });
    } else if (route.matched.length > 3) {
        await router.push({ name: moduleRoute.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"
                />
            </template>
        </q-input>
    </q-form>
</template>

<style lang="scss">
#searchbar .q-field {
    min-width: 350px;
}

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