<script setup>
import { usePageTitle } from '../composables/Core/usePageTitle';
usePageTitle('List Products Market');

import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useNavigate } from '../composables/Core/useNavigate';
import { useAuth } from '../composables/Core/useAuth';
import SearchBar from '../Components/Core/Search/SearchBar.vue';
import ProductCard from '../Components/Market/ProductCard.vue';
import ProductListSkeleton from '../Components/Core/Skeleton/ProductListSkeleton.vue';
import LoadingSpinner from '../Components/LoadingSpinner.vue';

const props = defineProps({
    data: { type: Object, default: () => ({}) }
});

const { navigate } = useNavigate();
const { isUltimate, isSuperOperator, isOperator } = useAuth();

import { useProductStore } from '../stores/product';
const productStore = useProductStore();

const products = computed(() => productStore.products);
const loading = computed(() => productStore.loading);
const searchQuery = ref('');

const fetchProducts = async () => {
    // Only fetch if empty, productStore already handles the logic
    await productStore.fetchProducts();
};

const filteredProducts = computed(() => {
    if (!searchQuery.value) return products.value;
    const q = searchQuery.value.toLowerCase();
    return products.value.filter(p =>
        p.name.toLowerCase().includes(q) ||
        p.description?.toLowerCase().includes(q)
    );
});

const viewProduct = (product) => {
    if (props.data?.store_hash) {
        navigate({
            page: 'AssignProductToStore',
            props: {
                payload: { product_hashkey: product.hashkey, store_hashkey: props.data.store_hash }
            }
        });
        return;
    }
    navigate({
        page: 'BuyViewProductMarket',
        props: { target: product.hashkey }
    });
};

onMounted(() => {
    fetchProducts();
});
</script>

<template>
    <div class="list-products-page pb-5">
        <div class="tf-container mt-4">
            <div class="d-flex align-items-center justify-content-between mb-3">
                <div class="d-flex align-items-center gap-3">
                    <h3 class="fw_6 mb-0">Marketplace</h3>
                    <button v-if="isUltimate || isSuperOperator || isOperator" @click="navigate({ page: 'CreateProductUltimate' })"
                        class="btn btn-sm btn-primary rounded-pill px-3 py-1">
                        <i class="fas fa-plus me-1"></i> New Product
                    </button>
                </div>
                <div class="badge bg-soft-primary px-3 py-2 rounded-pill text-primary">
                    {{ filteredProducts.length }} Products
                </div>
            </div>

            <div v-if="data?.store_name" class="alert alert-info py-2 rounded-15 mb-4 animate-fade-in">
                <i class="fas fa-info-circle me-2"></i>
                Please select a product to add to <strong>{{ data.store_name }}</strong>
                <button @click="navigate({ page: 'ViewStoreMarket', props: { target: data.store_hash } })" class="btn btn-link btn-sm float-end p-0">Cancel</button>
            </div>

            <SearchBar v-model="searchQuery" placeholder="Search products..." class="mb-4" />

            <div v-if="loading" class="mt-2 text-center">
                <ProductListSkeleton :count="12" />
            </div>

            <div v-else-if="filteredProducts.length === 0" class="text-center py-5 no-results">
                <img src="https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/146710fe9ece.bin" style="width: 120px; opacity: 0.3;" class="mb-3">
                <h5>No products found</h5>
                <p class="text-muted">Try adjusting your search criteria</p>
            </div>

            <div v-else class="row g-3 product-grid">
                <div v-for="product in filteredProducts" :key="product.hashkey" class="col-6 col-md-4 col-lg-3">
                    <ProductCard :name="product.name" :price="product.price" :unit="product.unit"
                        :description="product.description" :image="product.photo ? product.photo[0] : ''"
                        @click="viewProduct(product)" />
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.badge.bg-soft-primary {
    background-color: rgba(66, 185, 131, 0.1);
}

.product-grid {
    animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.no-results {
    background: #f8f9fa;
    border-radius: 20px;
    border: 2px dashed #dee2e6;
}

:global(.dark-mode) .no-results {
    background: #1a1c20;
    border-color: #2c3e50;
}
</style>
