<template>
    <TransitionRoot :show="open" as="template" @after-leave="onQueryChange('')" appear>
        <Dialog as="div" class="relative z-10" @close="onClose">
            <TransitionChild as="template" enter="ease-out duration-300" enter-from="opacity-0" enter-to="opacity-100"
                leave="ease-in duration-200" leave-from="opacity-100" leave-to="opacity-0">
                <div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-25 backdrop-blur" />
            </TransitionChild>

            <div class="fixed inset-0 z-10 p-4 overflow-y-auto sm:p-6 md:p-20">
                <TransitionChild as="template" enter="ease-out duration-300" enter-from="opacity-0 scale-95"
                    enter-to="opacity-100 scale-100" leave="ease-in duration-200" leave-from="opacity-100 scale-100"
                    leave-to="opacity-0 scale-95">
                    <DialogPanel
                        class="max-w-2xl mx-auto overflow-hidden transition-all transform bg-white divide-y divide-gray-500 shadow-2xl divide-opacity-10 rounded-xl bg-opacity-80 ring-0 ring-black ring-opacity-5">
                        <Combobox>
                            <div class="relative">
                                <MagnifyingGlassIcon
                                    class="pointer-events-none absolute top-3.5 left-4 h-5 w-5 text-gray-900 text-opacity-40"
                                    aria-hidden="true" />
                                <ComboboxInput :autofocus="false"
                                    class="w-full h-12 pr-4 text-gray-900 placeholder-gray-500 bg-white border-0 pl-11 focus:ring-0 sm:text-sm"
                                    placeholder="Cari menu..." @change="onQueryChange($event.target.value)" />
                            </div>

                            <ComboboxOptions v-if="query === '' || filteredMenus.length > 0" static
                                class="overflow-y-auto divide-y divide-gray-500 max-h-80 scroll-py-2 divide-opacity-10">
                                <li class="p-2" v-if="filteredMenus.length > 0 || recent.length > 0">
                                    <h2 v-if="query === '' && recent.length > 0"
                                        class="px-3 mt-4 mb-2 text-xs font-semibold text-gray-900">
                                        Pencarian terakhir</h2>
                                    <ul class="text-sm text-gray-700">
                                        <ComboboxOption as="template" v-for="menu in query === '' ? recent : filteredMenus"
                                            :key="menu.href" v-slot="{ active }">
                                            <li @click="openMenu(menu)"
                                                :class="['flex cursor-pointer select-none items-center rounded-md px-3 py-2', active && 'bg-gray-900 bg-opacity-5 text-gray-900']">
                                                <component :is="menu.icon"
                                                    :class="['h-6 w-6 flex-none text-gray-900 text-opacity-40', active && 'text-opacity-100']"
                                                    aria-hidden="true" />
                                                <span class="flex-auto ml-3 truncate">
                                                    {{ menu.name }}
                                                </span>
                                                <span v-if="active" class="flex-none ml-3 text-gray-500">
                                                    Buka
                                                </span>

                                            </li>
                                        </ComboboxOption>
                                    </ul>
                                </li>
                            </ComboboxOptions>

                            <div v-if="query !== '' && filteredMenus.length === 0" class="px-6 text-center py-14 sm:px-14">
                                <!-- <FolderIcon class="w-6 h-6 mx-auto text-gray-900 text-opacity-40" aria-hidden="true" /> -->
                                <h2 class="font-semibold text-slate-900">Tidak ada hasil</h2>

                                <p class="mt-2 text-sm leading-6 text-slate-600">
                                    Kami tidak dapat menemukan menu apa pun dengan istilah itu saat ini, silahkan gunakan
                                    kata kunci lainnya.
                                </p>
                            </div>
                        </Combobox>
                    </DialogPanel>
                </TransitionChild>
            </div>
        </Dialog>
    </TransitionRoot>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { MagnifyingGlassIcon } from '@heroicons/vue/20/solid'
import { FolderIcon } from '@heroicons/vue/24/outline'
import {
    Combobox,
    ComboboxInput,
    ComboboxOptions,
    ComboboxOption,
    Dialog,
    DialogPanel,
    TransitionChild,
    TransitionRoot,
} from '@headlessui/vue'
import { useMenuStore } from '@/stores/menu';
import { useRouter } from 'vue-router';

// const menus = [
//     { id: 1, name: 'Workflow Inc. / Website Redesign', url: '#' },
// ]
const nav = useMenuStore()
const menus = nav.navigation

// var recent = computed(() => readRecentMenu())

const props = defineProps({
    open: Boolean
})

const emit = defineEmits(['onClose'])

function searchMenus(query: string) {
    const result: typeof menus = []
    menus.forEach((menu) => {
        if (menu.children.length > 0) {
            menu.children.forEach((child) => {
                if (child.children.length > 0) {
                    child.children.forEach((grandChild) => {
                        if (grandChild.name.toLowerCase().includes(query.toLowerCase())) {
                            result.push(grandChild)
                        }
                    })
                } else {
                    if (child.name.toLowerCase().includes(query.toLowerCase())) {
                        result.push(child)
                    }
                }
            })
        } else {
            if (menu.name.toLowerCase().includes(query.toLowerCase())) {
                result.push(menu)
            }
        }

    })
    return result;
}

const route = useRouter()
const recent = computed(() => query.value === '' ? readRecentMenu() : [])
const open = ref(props.open)
const query = ref('')
const filteredMenus = computed(() =>
    query.value === ''
        ? []
        : searchMenus(query.value)
)

function onClose() {
    open.value = false
    emit('onClose')
}

function addMenuToRecent(menu: any) {
    const lastRecent = readRecentMenu()
    const index = lastRecent.findIndex((item: any) => item.href === menu.href)
    if (index > -1) {
        lastRecent.splice(index, 1)
    }
    lastRecent.unshift(menu)
    if (lastRecent.length > 5) {
        lastRecent.pop()
    }

    localStorage.setItem('recentmenu', JSON.stringify(lastRecent))
}
let debounceTimeout: ReturnType<typeof setTimeout> | null = null;
function onQueryChange(value: string) {
    if (debounceTimeout) {
        clearTimeout(debounceTimeout);
    }
    debounceTimeout = setTimeout(() => {
        // check if value is empty or only spaces
        if (value.trim() === '') {
            query.value = ''
            return
        }
        query.value = value
    }, 300);
}

function readRecentMenu() {
    const recent = localStorage.getItem('recentmenu')
    if (recent) {
        return JSON.parse(recent)
    }
    return []
}

function openMenu(menu: typeof menus[0]) {
    addMenuToRecent(menu)
    route.push(menu.href)
    onClose()
}

watch(() => props.open, (value) => {
    open.value = value;
});

</script>