<template>
    <ul
        class="absolute top-0 z-30 flex flex-col w-full gap-1 p-2 mx-auto bg-white rounded-lg shadow-lg"
        v-if="results.length > 0 || q.length > 0"
    >
        <template v-if="results.length > 0 && !loading">
            <li
                class="w-full"
                v-for="result in results"
                :key="target + '_' + result.objectID"
            >
                <a
                    class="flex items-center justify-start w-full gap-2 p-2 transition-all rounded-lg hover:bg-blue-200"
                    :href="resultUrl(result)"
                >
                    <img
                        v-if="result.profile_photo_url"
                        class="w-10 h-10 rounded-full"
                        :src="result.profile_photo_url"
                        :alt="result.name"
                    />
                    <span class="flex flex-col gap-1">
                        <span class="line-clamp-1">
                            {{ result.title || result.name }}
                        </span>
                        <span class="text-xs text-gray-200 line-clamp-3">
                            {{ result.description || result.tag_line }}
                        </span>
                    </span>
                </a>
            </li>
            <li>
                <p class="text-xs text-gray-200 text-end">
                    {{ results.length }} out of {{ rawResults.nbHits }} results
                </p>
            </li>
        </template>
        <template v-else-if="results.length <= 0 && !loading">
            <li class="py-2">
                <p class="text-xs text-gray-200 text-end">No results found</p>
            </li>
        </template>
        <template v-else>
            <li class="py-2">
                <p class="text-xs text-gray-200 text-start">Loading...</p>
            </li>
        </template>
    </ul>
</template>

<script>
import algoliasearch from "algoliasearch";
import { Link } from "@inertiajs/inertia-vue3";
import _ from "lodash";

export default {
    methods: {
        async fetchSearchResults() {
            // debounce the search using lodash _.debounce
            if (this.q.length < 1) {
                this.results = [];
                return;
            }
            this.loading = true;
            _.debounce(async () => {
                const client = algoliasearch(
                    this.$page.props.algolia.id,
                    this.$page.props.algolia.key
                );
                const index = client.initIndex(this.target.toLowerCase());
                const results = await index.search(this.q, {
                    hitsPerPage: 5, // show only 5 results
                });
                this.rawResults = results;
                this.loading = false;
                // filter out the results that have the value is_public = 0, and any result whose status != Open
                this.results = this.filterResults(results.hits);
            }, 100)();
        },
        resultUrl(result) {
            if (this.target == "Projects")
                return route("project.show", result.slug);
            if (this.target == "Engineers")
                return route("engineer.profile") + "/" + result.slug;
            if (this.target == "Firms")
                return route("firm.profile") + "/" + result.slug;
            if (this.target == "Services")
                return route("service.show", result.slug);
        },
        filterResults(results) {
            if (this.target == "Projects")
                return results.filter(
                    (result) => result.is_public == 1 && result.status == "Open"
                );
            else if (this.target == "Engineers") return results;
            else if (this.target == "Firms") return results;
            else if (this.target == "Services")
                return results.filter((result) => result.status == "Published");
            else return results;
        },
    },
    props: {
        target: {
            type: String,
            required: true,
        },
        q: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            loading: false,
            rawResults: [],
            results: [],
        };
    },
    watch: {
        q: {
            handler: function () {
                this.fetchSearchResults();
            },
            immediate: true,
        },
    },
};
</script>
