// noqa: js-006 - async init pattern is safe, loadData has try/catch
// 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: ''
        },

        // Selected vendor (for prominent display and filtering)
        selectedVendor: null,

        // Tom Select instance
        vendorSelectInstance: null,

        // Pagination
        pagination: {
            page: 1,
            per_page: 20,
            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() {
            // Load i18n translations
            await I18n.loadModule('catalog');

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

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

            // Load platform settings for rows per page
            if (window.PlatformSettings) {
                this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
            }

            // Initialize Tom Select for vendor filter
            this.initVendorSelect();

            // Check localStorage for saved vendor
            const savedVendorId = localStorage.getItem('vendor_products_selected_vendor_id');
            if (savedVendorId) {
                adminVendorProductsLog.info('Restoring saved vendor:', savedVendorId);
                // Restore vendor after a short delay to ensure TomSelect is ready
                setTimeout(async () => {
                    await this.restoreSavedVendor(parseInt(savedVendorId));
                }, 200);
                // Load stats but not products (restoreSavedVendor will do that)
                await this.loadStats();
            } else {
                // No saved vendor - load all data including unfiltered products
                await Promise.all([
                    this.loadStats(),
                    this.loadProducts()
                ]);
            }

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

        /**
         * Restore saved vendor from localStorage
         */
        async restoreSavedVendor(vendorId) {
            try {
                const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
                if (this.vendorSelectInstance && vendor) {
                    // Add the vendor as an option and select it
                    this.vendorSelectInstance.addOption({
                        id: vendor.id,
                        name: vendor.name,
                        vendor_code: vendor.vendor_code
                    });
                    this.vendorSelectInstance.setValue(vendor.id, true);

                    // Set the filter state
                    this.selectedVendor = vendor;
                    this.filters.vendor_id = vendor.id;

                    adminVendorProductsLog.info('Restored vendor:', vendor.name);

                    // Load products with the vendor filter applied
                    await this.loadProducts();
                }
            } catch (error) {
                adminVendorProductsLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
                localStorage.removeItem('vendor_products_selected_vendor_id');
                // Load unfiltered products as fallback
                await this.loadProducts();
            }
        },

        /**
         * Initialize Tom Select for vendor autocomplete
         */
        initVendorSelect() {
            const selectEl = this.$refs.vendorSelect;
            if (!selectEl) {
                adminVendorProductsLog.warn('Vendor select element not found');
                return;
            }

            // Wait for Tom Select to be available
            if (typeof TomSelect === 'undefined') {
                adminVendorProductsLog.warn('TomSelect not loaded, retrying in 100ms');
                setTimeout(() => this.initVendorSelect(), 100);
                return;
            }

            this.vendorSelectInstance = new TomSelect(selectEl, {
                valueField: 'id',
                labelField: 'name',
                searchField: ['name', 'vendor_code'],
                placeholder: 'Filter by vendor...',
                allowEmptyOption: true,
                load: async (query, callback) => {
                    try {
                        const response = await apiClient.get('/admin/vendors', {
                            search: query,
                            limit: 50
                        });
                        callback(response.vendors || []);
                    } catch (error) {
                        adminVendorProductsLog.error('Failed to search vendors:', error);
                        callback([]);
                    }
                },
                render: {
                    option: (data, escape) => {
                        return `<div class="flex items-center justify-between py-1">
                            <span>${escape(data.name)}</span>
                            <span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
                        </div>`;
                    },
                    item: (data, escape) => {
                        return `<div>${escape(data.name)}</div>`;
                    }
                },
                onChange: (value) => {
                    if (value) {
                        const vendor = this.vendorSelectInstance.options[value];
                        this.selectedVendor = vendor;
                        this.filters.vendor_id = value;
                        // Save to localStorage
                        localStorage.setItem('vendor_products_selected_vendor_id', value.toString());
                    } else {
                        this.selectedVendor = null;
                        this.filters.vendor_id = '';
                        // Clear from localStorage
                        localStorage.removeItem('vendor_products_selected_vendor_id');
                    }
                    this.pagination.page = 1;
                    this.loadProducts();
                    this.loadStats();
                }
            });

            adminVendorProductsLog.info('Vendor select initialized');
        },

        /**
         * Clear vendor filter
         */
        clearVendorFilter() {
            if (this.vendorSelectInstance) {
                this.vendorSelectInstance.clear();
            }
            this.selectedVendor = null;
            this.filters.vendor_id = '';
            // Clear from localStorage
            localStorage.removeItem('vendor_products_selected_vendor_id');
            this.pagination.page = 1;
            this.loadProducts();
            this.loadStats();
        },

        /**
         * Load product statistics
         */
        async loadStats() {
            try {
                const params = new URLSearchParams();
                if (this.filters.vendor_id) {
                    params.append('vendor_id', this.filters.vendor_id);
                }
                const url = params.toString() ? `/admin/vendor-products/stats?${params}` : '/admin/vendor-products/stats';
                const response = await apiClient.get(url);
                this.stats = response;
                adminVendorProductsLog.info('Loaded stats:', this.stats);
            } catch (error) {
                adminVendorProductsLog.error('Failed to load stats:', 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(I18n.t('catalog.messages.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();
            }
        }
    };
}
