<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>
          <button
            v-for="manga in results"
            :key="manga.id"
            @click="handleMangaClick(manga.id)"
            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>
          </button>
        </div>
      </template>

      <template v-else-if="hasSearched">
        <div class="py-2">
          <button
            @click="handleAddMangaClick"
            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>
          </button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
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 router = useRouter();
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 handleMangaClick = (id) => {
  router.push(`/manga/${id}`);
  isOpen.value = false;
  query.value = '';
  hasSearched.value = false;
};

const handleAddMangaClick = () => {
  router.push(`/add${query.value ? `?q=${encodeURIComponent(query.value)}` : ''}`);
  isOpen.value = false;
  query.value = '';
  hasSearched.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>
