<template>
    <div class="relative mb-4">
        <!-- <label for="mimetype-input" class="block text-sm font-medium text-gray-700">Search for Mimetypes</label> -->
        <input id="mimetype-input" v-model="newExtension" type="text" placeholder="Enter Mimetype Name"
            class="block w-full border border-gray-300 rounded-lg px-4 py-2 focus:ring-blue-500 focus:border-blue-500"
            :class="inputElClass" @input="handleInputChange" @keydown.down="onArrowDown" @keydown.up="onArrowUp"
            @keydown.prevent.enter="onEnter">
        </input>
        <svg class="w-4 h-4 absolute left-2.5 top-3.5" v-show="newExtension.length < 2"
            xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <svg class="w-4 h-4 absolute left-2.5 top-3.5" v-show="newExtension.length >= 2"
            xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"
            @click="clearInput">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
        </svg>

        <ul v-if="showDropdown && filteredMimetypes.length"
            class="bg-white dark:bg-slate-800 w-full mt-2 max-h-28 overflow-y-auto scroll-smooth">
            <li v-for="(mimeType, index) in filteredMimetypes" :key="index" @click="selectResult(mimeType)"
                class="pl-8 pr-2 py-1 border-b-2 border-gray-100 relative cursor-pointer hover:bg-blue-500 hover:text-white"
                :class="{
                    'bg-blue-500 text-white': selectedIndex === index,
                    'bg-white text-gray-900': selectedIndex !== index
                }" :ref="(el) => {
            if (ul) {
                ul[index] = el as HTMLLIElement;
            }
        }">
                <svg class="absolute w-4 h-4 left-2 top-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
                    fill="currentColor">
                    <path fill-rule="evenodd"
                        d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z"
                        clip-rule="evenodd" />
                </svg>
                <span>{{ mimeType }}</span>
            </li>
        </ul>
    </div>
</template>

<script lang="ts" setup>
import { ref, Ref, watch, computed } from 'vue';
// import mime from 'mime';

const emit = defineEmits(['onSelectResult', 'onClearInput'])

const props = defineProps({
    borderless: Boolean,
    transparent: Boolean,
    mimeTypes: {
        type: Array as () => string[],
        required: true
    },
    // form: Object,  
    // isValidMimeType: Function,
});

const newExtension = ref('');
const showDropdown = ref(false);
const filteredMimetypes = ref<string[]>([]);
const selectedIndex: Ref<number> = ref(0);
const ul: Ref<HTMLLIElement[] | null> = ref<HTMLLIElement[]>([]);

watch(selectedIndex, (selectedIndex: number) => {
    if (selectedIndex != null && ul.value != null) {
        const currentElement: HTMLLIElement = ul.value[selectedIndex];
        currentElement &&
            currentElement?.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
                inline: 'start',
            });
    }
});

const inputElClass = computed(() => {
    const base = [
        'block p-2.5 w-full z-20 text-sm text-gray-900 bg-gray-50 rounded-r-lg',
        'dark:placeholder-gray-400 dark:text-white dark:focus:border-blue-500',
        'h-12',
        props.borderless ? 'border-0' : 'border',
        props.transparent ? 'bg-transparent' : 'bg-white dark:bg-slate-800',
    ];
    base.push('pl-10');
    return base;
});

const handleInputChange = (e: Event) => {
    const target = <HTMLInputElement>e.target;
    newExtension.value = target.value;

    if (newExtension.value.length >= 2) {
        showDropdown.value = true;
        filteredMimetypes.value = props.mimeTypes.filter(mimeType =>
            mimeType.toLowerCase().includes(newExtension.value.toLowerCase())
        );
    } else {
        showDropdown.value = false;
    }
};

const selectResult = (mimeType: string) => {
    showDropdown.value = false;
    newExtension.value = '';
    selectedIndex.value = -1;
    emit('onSelectResult', mimeType);
};

const clearInput = () => {
    newExtension.value = '';
    showDropdown.value = false;
    // props.form.name = '';
    // props.resetFileExtensions();
    emit('onClearInput');
};

const onArrowDown = () => {
    if (filteredMimetypes.value.length > 0) {
        selectedIndex.value = selectedIndex.value === filteredMimetypes.value.length - 1 ? 0 : selectedIndex.value + 1;
    }
};

const onArrowUp = () => {
    if (filteredMimetypes.value.length > 0) {
        selectedIndex.value = selectedIndex.value == 0 || selectedIndex.value == -1 ? filteredMimetypes.value.length - 1 : selectedIndex.value - 1;
    }
};

const onEnter = () => {
    if (Array.isArray(filteredMimetypes.value) && filteredMimetypes.value.length && selectedIndex.value !== -1 && selectedIndex.value < filteredMimetypes.value.length) {
        const mimeType = filteredMimetypes.value[selectedIndex.value];
        selectResult(mimeType);
    }
};
</script>
