<template>
    <div class="space-y-5">
        {{ addProductStore.form }}

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Product name" name="productName">
                <UInput v-model="addProductStore.form.product.name" placeholder="Enter product name" class="w-full" />
            </UFormField>
            <UFormField label="Reference (SKU)" name="productReference">
                <UInput v-model="addProductStore.form.product.reference" placeholder="e.g. REF-001" class="w-full" />
            </UFormField>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <UFormField label="Podsumowanie">
                <ProductEditor v-model="addProductStore.form.product.description_short" />
            </UFormField>
            <UFormField label="Description">
                <ProductEditor v-model="addProductStore.form.product.description" />
            </UFormField>
        </div>

        <fieldset
            class="rounded-xl border border-(--border-light) dark:border-(--border-dark) p-4 space-y-3 bg-white dark:bg-neutral-900">
            <legend class="px-1 block font-medium text-default text-[16px]">Images</legend>
            {{ addProductStore.images }}

            <div class="flex items-start gap-3 flex-wrap">
                <div v-for="(img, idx) in addProductStore.images" :key="idx" class="relative group shrink-0">
                    <div class="relative w-36 h-36 rounded-xl overflow-hidden border-2 transition-colors" :class="img.cover
                        ? 'border-sky-500'
                        : 'border-(--border-light) dark:border-(--border-dark)'">

                        <img :src="img.previewUrl" @error="onImgError"
                            class="w-full h-full object-contain bg-white dark:bg-neutral-900" />

                        <div v-if="img.uploading" class="absolute inset-0 flex items-center justify-center bg-black/50">
                            <UIcon name="svg-spinners:ring-resize" class="text-2xl text-white" />
                        </div>

                        <div v-else-if="img.error"
                            class="absolute bottom-0 left-0 right-0 bg-red-500/80 text-white text-[10px] px-1 py-0.5 text-center truncate">
                            {{ img.error }}
                        </div>


                        <div v-if="img.cover"
                            class="absolute top-1.5 left-1.5 bg-sky-500 text-white text-[10px] font-semibold px-1.5 py-0.5 rounded-full leading-none">
                            ★ Cover
                        </div>

                        <div v-if="!img.uploading"
                            class="absolute inset-0 flex flex-col items-center justify-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity bg-black/50">
                            <button v-if="!img.cover" type="button"
                                class="flex items-center gap-1 px-2 py-1 rounded-md bg-white/20 hover:bg-sky-500 text-white text-xs font-medium transition-colors"
                                @click.stop="addProductStore.setCover(idx)">
                                <UIcon name="i-lucide-star" class="text-sm" />
                                Set cover
                            </button>
                            <button type="button"
                                class="flex items-center gap-1 px-2 py-1 rounded-md bg-white/20 hover:bg-red-500 text-white text-xs font-medium transition-colors"
                                @click.stop="addProductStore.removeImage(idx)">
                                <UIcon name="i-lucide-trash-2" class="text-sm" />
                                Remove
                            </button>
                        </div>
                    </div>
                </div>

                <label
                    class="w-36 h-36 shrink-0 flex flex-col items-center justify-center gap-1 rounded-xl border-2 border-dashed border-(--border-light) dark:border-(--border-dark) cursor-pointer hover:border-sky-400 hover:text-sky-400 transition-colors text-gray-400"
                    @dragover.prevent @drop.prevent="onDrop">
                    <UIcon name="i-lucide-plus" class="text-2xl" />
                    <span class="text-xs">Add image</span>
                    <input type="file" accept="image/*" multiple class="hidden" @change="onFileChange" />
                </label>
            </div>
        </fieldset>

        <div class="space-y-2">
            <p class="text-sm font-medium text-black dark:text-white">Powiązany produkt</p>

            <UInput v-model="relatedSearch" placeholder="Search and add Powiązany produkt" icon="i-lucide-search"
                class="w-full" />

            <div v-if="addProductStore.relatedProducts.length > 0"
                class="rounded-lg border border-(--border-light) dark:border-(--border-dark) overflow-hidden">
                <div v-for="p in addProductStore.relatedProducts" :key="p.id_product"
                    class="flex items-center justify-between px-3 py-2 text-sm text-black dark:text-white border-b border-(--border-light) dark:border-(--border-dark) last:border-0">
                    <span>{{ p.name }}</span>
                    <button type="button" @click="removeRelated(p.id_product)"
                        class="text-gray-400 hover:text-red-500 transition-colors ml-2">
                        <UIcon name="i-lucide-x" class="text-base" />
                    </button>
                </div>
            </div>

            <USelect :items="relatedResults" value-key="product_id" />
            <div v-if="relatedResults.length > 0"
                class="rounded-lg border border-(--border-light) dark:border-(--border-dark) overflow-hidden bg-white dark:bg-neutral-900">
                <button v-for="p in relatedResults" :key="p.id_product" type="button"
                    class="w-full text-left px-3 py-2 text-sm text-black dark:text-white hover:bg-gray-50 dark:hover:bg-neutral-800 transition-colors border-b border-(--border-light) dark:border-(--border-dark) last:border-0"
                    @click="addRelated(p)">
                    {{ p.name }}
                    <span class="text-gray-400 ml-1">{{ p.reference }}</span>
                </button>
            </div>

        </div>

        <fieldset
            class="rounded-xl border border-(--border-light) dark:border-(--border-dark) p-4 space-y-3 bg-white dark:bg-neutral-900">
            <legend class="px-1 block font-medium text-default text-[16px]">Kategorie</legend>

            <UInput v-model="categorySearch" placeholder="Search" class="w-52" icon="i-lucide-search" />
            <div v-if="addProductStore.selectedCategories.length > 0"
                class="rounded-lg border border-(--border-light) dark:border-(--border-dark) p-2 min-h-10 flex flex-wrap gap-2">
                <span v-for="cat in addProductStore.selectedCategories" :key="cat.id_category"
                    class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-sky-100 dark:bg-sky-900 text-sky-700 dark:text-sky-300">
                    {{ cat.name }}
                    <button type="button" @click="removeCategory(cat.id_category)"
                        class="text-sky-500 hover:text-sky-700 dark:hover:text-sky-200 leading-none ml-0.5">
                        <UIcon name="i-lucide-x" />
                    </button>
                </span>
            </div>

            <div class="space-y-0.5 overflow-y-auto flex">
                <UNavigationMenu orientation="vertical" type="multiple" :items="filteredCategories" :ui="{
                    root: 'w-auto'
                }">
                    <template #item="{ item }">
                        <div
                            class="flex items-center gap-2.5 cursor-pointer rounded px-1.5 py-1 hover:bg-gray-50 dark:hover:bg-neutral-800 transition-colors"
                            @click.stop="toggleCategory({ id_category: item.params?.category_id, name: item.label as string })">
                            <UCheckbox :model-value="isCategorySelected(item.params?.category_id)"
                                color="info" />
                            <span class="text-sm text-black dark:text-white">{{ item.label }}</span>
                        </div>
                    </template>
                </UNavigationMenu>
            </div>

            <UButton size="xs" variant="outline" color="neutral" icon="i-lucide-plus">
                Add new category
            </UButton>
        </fieldset>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAddProductStore } from '@/stores/admin/addProduct'
import type { ProductCategory, ProductRelated } from '@/types/product'
import errorImg from '@/assets/error.svg'
import { useFetchJson } from '@/composable/useFetchJson'
import { watch } from 'vue'
import type { NavigationMenuItem } from '@nuxt/ui'

const addProductStore = useAddProductStore()

const loading = ref(false)

function onImgError(e: Event) {
    const target = e.target as HTMLImageElement
    target.src = errorImg
}

function onFileChange(e: Event) {
    const files = (e.target as HTMLInputElement).files
    if (files && files.length > 0) addProductStore.addImageFiles(files)
        ; (e.target as HTMLInputElement).value = ''
}

function onDrop(e: DragEvent) {
    const files = e.dataTransfer?.files
    if (files && files.length > 0) addProductStore.addImageFiles(files)
}

// categories
const categorySearch = ref('')
const allCategories = computed(() => adaptCategory(addProductStore.categories))
function adaptCategory(menu: NavigationMenuItem[]) {
    for (const item of menu) {
        if (item.children && item.children.length > 0) {
            item.open = true
            adaptCategory(item.children);

            item.children.unshift({
                label: item.label,
                icon: 'i-lucide-book-open',
                params: item.params,
            })
        } else {
            item.icon = 'i-lucide-file-text'
        }
    }
    return menu;
}

//there have to be request on filter category (but have to  return like parent => children =>)
const filteredCategories = computed(() => {
    const q = categorySearch.value.trim().toLowerCase()
    if (!q) return allCategories.value
    return allCategories.value.filter(c => c.name.toLowerCase().includes(q))
})

function isCategorySelected(id: number) {
    return addProductStore.selectedCategories.some(c => c.id_category === id)
}

function toggleCategory(cat: ProductCategory) {
    console.log(cat);
    
    if (isCategorySelected(cat.id_category)) {
        removeCategory(cat.id_category)
    } else {
        addProductStore.selectedCategories.push(cat)
    }
}

function removeCategory(id: number) {
    const idx = addProductStore.selectedCategories.findIndex(c => c.id_category === id)
    if (idx !== -1) addProductStore.selectedCategories.splice(idx, 1)
}

// related products
const relatedSearch = ref('')
const relatedResults = ref<ProductRelated[]>([])

let searchTimer: ReturnType<typeof setTimeout> | null = null
watch(relatedSearch, (q) => {
    if (searchTimer) clearTimeout(searchTimer)
    if (!q.trim()) { relatedResults.value = []; return }
    searchTimer = setTimeout(async () => {
        await fetchProducts(q)
    }, 1000)
})

function addRelated(product: ProductRelated) {
    if (!addProductStore.relatedProducts.some(p => p.id_product === product.id_product)) {
        addProductStore.relatedProducts.push(product)
    }
    relatedSearch.value = ''
    relatedResults.value = []
}

function removeRelated(id: number) {
    const idx = addProductStore.relatedProducts.findIndex(p => p.id_product === id)
    if (idx !== -1) addProductStore.relatedProducts.splice(idx, 1)
}

const products = ref()
async function fetchProducts(q: string) {
    if (!q.trim()) {
        products.value = []
        return
    }

    loading.value = true
    relatedResults.value = []
    try {
        const query = `name=~${q.trim()}`
        const result = await useFetchJson(
            `/api/v1/restricted/product/list?${query}`
        )

        relatedResults.value = (result.items ?? result) as ProductRelated[]
    } catch (e) {
        console.log(e);

    } finally {
        loading.value = false
    }
}

await addProductStore.loadCategories()    
</script>
