<template>
    <div ref="searchRef" class="relative flex-1 max-w-xl mx-4">
        <div class="flex items-center py-1">
            <MagnifyingGlassIcon class="h-5 w-5 text-white" />
            <input
                type="text"
                v-model="query"
                @input="handleInput"
                @focus="isOpen = true"
                placeholder="Rechercher"
                class="appearance-none outline-none ml-2 pl-0 bg-transparent border-b border-white w-full placeholder:text-white text-white py-1 px-2 leading-tight transition-all duration-500 ease-in-out focus:placeholder:text-opacity-0 focus:border-opacity-0" />
        </div>

        <div
            v-if="isOpen && query.trim()"
            class="absolute w-full mt-2 bg-gray-800/95 backdrop-blur-sm rounded-lg shadow-lg border border-gray-700 max-h-96 overflow-y-auto z-50">
            <div v-if="loading" class="p-4 text-center text-gray-400"> Chargement... </div>

            <template v-else-if="results.length > 0">
                <div class="py-2">
                    <h3 class="px-4 py-2 text-sm font-semibold text-gray-400"> Mangas existants </h3>
                    <RouterLink
                        v-for="manga in results"
                        :key="manga.id"
                        :to="{ name: 'manga-details', params: { id: manga.id } }"
                        @click="
                            () => {
                                isOpen = false;
                                query = '';
                                hasSearched = false;
                            }
                        "
                        class="w-full px-4 py-2 flex items-center gap-3 hover:bg-gray-700/50 text-white">
                        <img :src="manga.thumbnailUrl" :alt="manga.title" class="w-10 h-14 object-cover rounded" />
                        <div class="text-left">
                            <div class="font-medium">{{ manga.title }}</div>
                            <div class="text-sm text-gray-400">{{ manga.author }} ({{ manga.publicationYear }})</div>
                        </div>
                    </RouterLink>
                </div>
            </template>

            <template v-else-if="hasSearched">
                <div class="py-2">
                    <RouterLink
                        :to="{ name: 'add-manga', query: query ? { q: query } : undefined }"
                        @click="
                            () => {
                                isOpen = false;
                                query = '';
                                hasSearched = false;
                            }
                        "
                        class="w-full px-4 py-2 flex items-center gap-2 text-green-400 hover:bg-gray-700/50">
                        <PlusIcon class="h-5 w-5" />
                        <span>Ajouter "{{ query }}"</span>
                    </RouterLink>
                </div>
            </template>
        </div>
    </div>
</template>

<script setup>
    import { ref, onMounted, onUnmounted } from 'vue';
    import { MagnifyingGlassIcon, PlusIcon } from '@heroicons/vue/24/outline';
    import { ApiMangaRepository } from '../../../domain/manga/infrastructure/api/apiMangaRepository';
    import { SearchMangas } from '../../../domain/manga/application/queries/searchMangas';

    const mangaRepository = new ApiMangaRepository();
    const searchMangas = new SearchMangas(mangaRepository);

    const searchRef = ref(null);
    const query = ref('');
    const results = ref([]);
    const isOpen = ref(false);
    const loading = ref(false);
    const hasSearched = ref(false);

    let searchTimeout;

    const handleInput = () => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(searchManga, 300);
    };

    const searchManga = async () => {
        if (!query.value.trim()) {
            results.value = [];
            hasSearched.value = false;
            return;
        }

        loading.value = true;
        try {
            const response = await searchMangas.execute(query.value);
            results.value = Array.isArray(response) ? response : response.items || [];
            hasSearched.value = true;
            console.log('Résultats de recherche:', results.value);
        } catch (error) {
            console.error('Search error:', error);
            results.value = [];
        } finally {
            loading.value = false;
        }
    };

    const handleClickOutside = event => {
        if (searchRef.value && !searchRef.value.contains(event.target)) {
            isOpen.value = false;
        }
    };

    onMounted(() => {
        document.addEventListener('mousedown', handleClickOutside);
    });

    onUnmounted(() => {
        document.removeEventListener('mousedown', handleClickOutside);
        clearTimeout(searchTimeout);
    });
</script>
