<script setup lang="ts">
import { Icon } from '#components'
import { search, type Result } from '~/openapi/search'

const route = useRoute()
const searchQuery = ref(route.query.title as string || '')

const results = ref<Result[]>([])
const isLoading = ref(false)
const error = ref<unknown>(null)

watchEffect(async () => {
    if (!searchQuery.value) return

    try {
        isLoading.value = true
        error.value = null
        console.log("SEARCHING")
        const response = await search({ title: searchQuery.value })
        results.value = response.data.results || []
    } catch (err) {
        error.value = err
        console.error('Search failed:', err)
    } finally {
        isLoading.value = false
    }
}, {
    flush: 'post'
})
</script>

<template>
    <div>
        <div v-if="isLoading">
            Loading results...
        </div>

        <div v-if="error">
            Error loading results: {{ error }}
        </div>

        <div v-if="results.length > 0"
            class="grid grid-cols-[repeat(auto-fill,16rem)] justify-around gap-8 grid-flow-row">
            <div v-for="item in results" :key="item.id" class="flex w-[16rem]">
                <NuxtLink :to="`/anime/${item.id}`" class="w-full">
                    <div v-if="item.material_data?.anime_poster_url"
                        :style="{ 'background-image': 'url(' + item.material_data.anime_poster_url + ')' }"
                        :alt="item.title"
                        class="flex items-end justify-end p-2 rounded-md bg-cover bg-center bg-no-repeat h-96">
                        <div
                            class="flex items-center px-2 py-0.5 backdrop-blur-none bg-primary/75 text-background/80 rounded-sm text-xs">
                            <Icon name="gg:play-list" />
                            {{ item.material_data?.episodes_total }}
                            episode
                        </div>
                    </div>
                    <div>
                        <h3 className="text-xl font-semibold tracking-tight">{{ item.title }}</h3>
                    </div>
                </NuxtLink>
            </div>
        </div>

        <div v-if="!isLoading && !error && results.length === 0 && searchQuery">
            No results found for "{{ searchQuery }}"
        </div>
    </div>
</template>
