// static/admin/js/vendor-products.js
/**
 * Admin vendor products page logic
 * Browse vendor-specific product catalogs with override capability
 */

const adminVendorProductsLog = window.LogConfig.loggers.adminVendorProducts ||
    window.LogConfig.createLogger('adminVendorProducts', false);

adminVendorProductsLog.info('Loading...');

function adminVendorProducts() {
    adminVendorProductsLog.info('adminVendorProducts() called');

    return {
        // Inherit base layout state
        ...data(),

        // Set page identifier
        currentPage: 'vendor-products',

        // Loading states
        loading: true,
        error: '',

        // Products data
        products: [],
        stats: {
            total: 0,
            active: 0,
            inactive: 0,
            featured: 0,
            digital: 0,
            physical: 0,
            by_vendor: {}
        },

        // Filters
        filters: {
            search: '',
            vendor_id: '',
            is_active: '',
            is_featured: ''
        },

        // Available vendors for filter dropdown
        vendors: [],

        // Pagination
        pagination: {
            page: 1,
            per_page: 50,
            total: 0,
            pages: 0
        },

        // Product detail modal state
        showProductModal: false,
        selectedProduct: null,

        // Remove confirmation modal state
        showRemoveModal: false,
        productToRemove: null,
        removing: false,

        // Debounce timer
        searchTimeout: null,

        // Computed: Total pages
        get totalPages() {
            return this.pagination.pages;
        },

        // Computed: Start index for pagination display
        get startIndex() {
            if (this.pagination.total === 0) return 0;
            return (this.pagination.page - 1) * this.pagination.per_page + 1;
        },

        // Computed: End index for pagination display
        get endIndex() {
            const end = this.pagination.page * this.pagination.per_page;
            return end > this.pagination.total ? this.pagination.total : end;
        },

        // Computed: Page numbers for pagination
        get pageNumbers() {
            const pages = [];
            const totalPages = this.totalPages;
            const current = this.pagination.page;

            if (totalPages <= 7) {
                for (let i = 1; i <= totalPages; i++) {
                    pages.push(i);
                }
            } else {
                pages.push(1);
                if (current > 3) {
                    pages.push('...');
                }
                const start = Math.max(2, current - 1);
                const end = Math.min(totalPages - 1, current + 1);
                for (let i = start; i <= end; i++) {
                    pages.push(i);
                }
                if (current < totalPages - 2) {
                    pages.push('...');
                }
                pages.push(totalPages);
            }
            return pages;
        },

        async init() {
            adminVendorProductsLog.info('Vendor Products init() called');

            // Guard against multiple initialization
            if (window._adminVendorProductsInitialized) {
                adminVendorProductsLog.warn('Already initialized, skipping');
                return;
            }
            window._adminVendorProductsInitialized = true;

            // Load data in parallel
            await Promise.all([
                this.loadStats(),
                this.loadVendors(),
                this.loadProducts()
            ]);

            adminVendorProductsLog.info('Vendor Products initialization complete');
        },

        /**
         * Load product statistics
         */
        async loadStats() {
            try {
                const response = await apiClient.get('/admin/vendor-products/stats');
                this.stats = response;
                adminVendorProductsLog.info('Loaded stats:', this.stats);
            } catch (error) {
                adminVendorProductsLog.error('Failed to load stats:', error);
            }
        },

        /**
         * Load available vendors for filter
         */
        async loadVendors() {
            try {
                const response = await apiClient.get('/admin/vendor-products/vendors');
                this.vendors = response.vendors || [];
                adminVendorProductsLog.info('Loaded vendors:', this.vendors.length);
            } catch (error) {
                adminVendorProductsLog.error('Failed to load vendors:', error);
            }
        },

        /**
         * Load products with filtering and pagination
         */
        async loadProducts() {
            this.loading = true;
            this.error = '';

            try {
                const params = new URLSearchParams({
                    skip: (this.pagination.page - 1) * this.pagination.per_page,
                    limit: this.pagination.per_page
                });

                // Add filters
                if (this.filters.search) {
                    params.append('search', this.filters.search);
                }
                if (this.filters.vendor_id) {
                    params.append('vendor_id', this.filters.vendor_id);
                }
                if (this.filters.is_active !== '') {
                    params.append('is_active', this.filters.is_active);
                }
                if (this.filters.is_featured !== '') {
                    params.append('is_featured', this.filters.is_featured);
                }

                const response = await apiClient.get(`/admin/vendor-products?${params.toString()}`);

                this.products = response.products || [];
                this.pagination.total = response.total || 0;
                this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);

                adminVendorProductsLog.info('Loaded products:', this.products.length, 'of', this.pagination.total);
            } catch (error) {
                adminVendorProductsLog.error('Failed to load products:', error);
                this.error = error.message || 'Failed to load products';
            } finally {
                this.loading = false;
            }
        },

        /**
         * Debounced search handler
         */
        debouncedSearch() {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.pagination.page = 1;
                this.loadProducts();
            }, 300);
        },

        /**
         * Refresh products list
         */
        async refresh() {
            await Promise.all([
                this.loadStats(),
                this.loadVendors(),
                this.loadProducts()
            ]);
        },

        /**
         * View product details - navigate to detail page
         */
        viewProduct(productId) {
            adminVendorProductsLog.info('Navigating to product detail:', productId);
            window.location.href = `/admin/vendor-products/${productId}`;
        },

        /**
         * Show remove confirmation modal
         */
        confirmRemove(product) {
            this.productToRemove = product;
            this.showRemoveModal = true;
        },

        /**
         * Execute product removal from catalog
         */
        async executeRemove() {
            if (!this.productToRemove) return;

            this.removing = true;
            try {
                await apiClient.delete(`/admin/vendor-products/${this.productToRemove.id}`);

                adminVendorProductsLog.info('Removed product:', this.productToRemove.id);

                // Close modal and refresh
                this.showRemoveModal = false;
                this.productToRemove = null;

                // Show success notification
                Utils.showToast('Product removed from vendor catalog.', 'success');

                // Refresh the list
                await this.refresh();
            } catch (error) {
                adminVendorProductsLog.error('Failed to remove product:', error);
                this.error = error.message || 'Failed to remove product';
            } finally {
                this.removing = false;
            }
        },

        /**
         * Format price for display
         */
        formatPrice(price, currency = 'EUR') {
            if (price === null || price === undefined) return '-';
            return new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: currency || 'EUR'
            }).format(price);
        },

        /**
         * Pagination: Previous page
         */
        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadProducts();
            }
        },

        /**
         * Pagination: Next page
         */
        nextPage() {
            if (this.pagination.page < this.totalPages) {
                this.pagination.page++;
                this.loadProducts();
            }
        },

        /**
         * Pagination: Go to specific page
         */
        goToPage(pageNum) {
            if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
                this.pagination.page = pageNum;
                this.loadProducts();
            }
        }
    };
}
