// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/marketplace-products.js
/**
 * Admin marketplace products page logic
 * Browse the master product repository (imported from external sources)
 */

const adminMarketplaceProductsLog = window.LogConfig.loggers.adminMarketplaceProducts ||
    window.LogConfig.createLogger('adminMarketplaceProducts', false);

adminMarketplaceProductsLog.info('Loading...');

function adminMarketplaceProducts() {
    adminMarketplaceProductsLog.info('adminMarketplaceProducts() called');

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

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

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

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

        // Filters
        filters: {
            search: '',
            marketplace: '',
            store_name: '',
            is_active: '',
            is_digital: ''
        },

        // Selected store (for prominent display and filtering)
        selectedStore: null,

        // Tom Select instance
        storeSelectInstance: null,

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

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

        // Selection state
        selectedProducts: [],

        // Copy to store modal state
        showCopyModal: false,
        copying: false,
        copyForm: {
            store_id: '',
            skip_existing: true
        },
        targetStores: [],

        // 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() {
            adminMarketplaceProductsLog.info('Marketplace Products init() called');

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

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

            // Initialize Tom Select for store filter
            this.initStoreSelect();

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

            adminMarketplaceProductsLog.info('Marketplace Products initialization complete');
        },

        /**
         * Restore saved store from localStorage
         */
        async restoreSavedStore(storeId) {
            try {
                const store = await apiClient.get(`/admin/stores/${storeId}`);
                if (this.storeSelectInstance && store) {
                    // Add the store as an option and select it
                    this.storeSelectInstance.addOption({
                        id: store.id,
                        name: store.name,
                        store_code: store.store_code
                    });
                    this.storeSelectInstance.setValue(store.id, true);

                    // Set the filter state
                    this.selectedStore = store;
                    this.filters.store_name = store.name;

                    adminMarketplaceProductsLog.info('Restored store:', store.name);

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

        /**
         * Initialize Tom Select for store autocomplete
         */
        initStoreSelect() {
            const selectEl = this.$refs.storeSelect;
            if (!selectEl) {
                adminMarketplaceProductsLog.warn('Store select element not found');
                return;
            }

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

            this.storeSelectInstance = new TomSelect(selectEl, {
                valueField: 'id',
                labelField: 'name',
                searchField: ['name', 'store_code'],
                placeholder: 'Filter by store...',
                allowEmptyOption: true,
                load: async (query, callback) => {
                    try {
                        const response = await apiClient.get('/admin/stores', {
                            search: query,
                            limit: 50
                        });
                        callback(response.stores || []);
                    } catch (error) {
                        adminMarketplaceProductsLog.error('Failed to search stores:', 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.store_code || '')}</span>
                        </div>`;
                    },
                    item: (data, escape) => {
                        return `<div>${escape(data.name)}</div>`;
                    }
                },
                onChange: (value) => {
                    if (value) {
                        const store = this.storeSelectInstance.options[value];
                        this.selectedStore = store;
                        this.filters.store_name = store.name;
                        // Save to localStorage
                        localStorage.setItem('marketplace_products_selected_store_id', value.toString());
                    } else {
                        this.selectedStore = null;
                        this.filters.store_name = '';
                        // Clear from localStorage
                        localStorage.removeItem('marketplace_products_selected_store_id');
                    }
                    this.pagination.page = 1;
                    this.loadProducts();
                    this.loadStats();
                }
            });

            adminMarketplaceProductsLog.info('Store select initialized');
        },

        /**
         * Clear store filter
         */
        clearStoreFilter() {
            if (this.storeSelectInstance) {
                this.storeSelectInstance.clear();
            }
            this.selectedStore = null;
            this.filters.store_name = '';
            // Clear from localStorage
            localStorage.removeItem('marketplace_products_selected_store_id');
            this.pagination.page = 1;
            this.loadProducts();
            this.loadStats();
        },

        /**
         * Load product statistics
         */
        async loadStats() {
            try {
                const params = new URLSearchParams();
                if (this.filters.marketplace) {
                    params.append('marketplace', this.filters.marketplace);
                }
                if (this.filters.store_name) {
                    params.append('store_name', this.filters.store_name);
                }
                const url = params.toString() ? `/admin/products/stats?${params}` : '/admin/products/stats';
                const response = await apiClient.get(url);
                this.stats = response;
                adminMarketplaceProductsLog.info('Loaded stats:', this.stats);
            } catch (error) {
                adminMarketplaceProductsLog.error('Failed to load stats:', error);
            }
        },

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

        /**
         * Load target stores for copy functionality (actual store accounts)
         */
        async loadTargetStores() {
            try {
                const response = await apiClient.get('/admin/stores?is_active=true&limit=500');
                this.targetStores = response.stores || [];
                adminMarketplaceProductsLog.info('Loaded target stores:', this.targetStores.length);
            } catch (error) {
                adminMarketplaceProductsLog.error('Failed to load target stores:', 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.marketplace) {
                    params.append('marketplace', this.filters.marketplace);
                }
                if (this.filters.store_name) {
                    params.append('store_name', this.filters.store_name);
                }
                if (this.filters.is_active !== '') {
                    params.append('is_active', this.filters.is_active);
                }
                if (this.filters.is_digital !== '') {
                    params.append('is_digital', this.filters.is_digital);
                }

                const response = await apiClient.get(`/admin/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);

                adminMarketplaceProductsLog.info('Loaded products:', this.products.length, 'of', this.pagination.total);
            } catch (error) {
                adminMarketplaceProductsLog.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.loadProducts()
            ]);
        },

        // ─────────────────────────────────────────────────────────────────
        // Selection Management
        // ─────────────────────────────────────────────────────────────────

        /**
         * Check if a product is selected
         */
        isSelected(productId) {
            return this.selectedProducts.includes(productId);
        },

        /**
         * Toggle selection for a single product
         */
        toggleSelection(productId) {
            const index = this.selectedProducts.indexOf(productId);
            if (index === -1) {
                this.selectedProducts.push(productId);
            } else {
                this.selectedProducts.splice(index, 1);
            }
            adminMarketplaceProductsLog.info('Selection changed:', this.selectedProducts.length, 'selected');
        },

        /**
         * Toggle select all products on current page
         */
        toggleSelectAll(event) {
            if (event.target.checked) {
                // Select all on current page
                this.selectedProducts = this.products.map(p => p.id);
            } else {
                // Deselect all
                this.selectedProducts = [];
            }
            adminMarketplaceProductsLog.info('Select all toggled:', this.selectedProducts.length, 'selected');
        },

        /**
         * Clear all selections
         */
        clearSelection() {
            this.selectedProducts = [];
            adminMarketplaceProductsLog.info('Selection cleared');
        },

        // ─────────────────────────────────────────────────────────────────
        // Copy to Store Catalog
        // ─────────────────────────────────────────────────────────────────

        /**
         * Open copy modal for selected products
         */
        openCopyToStoreModal() {
            if (this.selectedProducts.length === 0) {
                this.error = 'Please select at least one product to copy';
                return;
            }
            this.copyForm.store_id = '';
            this.showCopyModal = true;
            adminMarketplaceProductsLog.info('Opening copy modal for', this.selectedProducts.length, 'products');
        },

        /**
         * Copy single product - convenience method for action button
         */
        copySingleProduct(productId) {
            this.selectedProducts = [productId];
            this.openCopyToStoreModal();
        },

        /**
         * Execute copy to store catalog
         */
        async executeCopyToStore() {
            if (!this.copyForm.store_id) {
                this.error = 'Please select a target store';
                return;
            }

            this.copying = true;
            try {
                const response = await apiClient.post('/admin/products/copy-to-store', {
                    marketplace_product_ids: this.selectedProducts,
                    store_id: parseInt(this.copyForm.store_id),
                    skip_existing: this.copyForm.skip_existing
                });

                adminMarketplaceProductsLog.info('Copy result:', response);

                // Show success message
                const copied = response.copied || 0;
                const skipped = response.skipped || 0;
                const failed = response.failed || 0;

                let message = `Successfully copied ${copied} product(s) to store catalog.`;
                if (skipped > 0) message += ` ${skipped} already existed.`;
                if (failed > 0) message += ` ${failed} failed.`;

                // Close modal and clear selection
                this.showCopyModal = false;
                this.clearSelection();

                // Show success notification
                Utils.showToast(message, 'success');
            } catch (error) {
                adminMarketplaceProductsLog.error('Failed to copy products:', error);
                const errorMsg = error.message || 'Failed to copy products to store catalog';
                this.error = errorMsg;
                Utils.showToast(errorMsg, 'error');
            } finally {
                this.copying = 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();
            }
        }
    };
}
