// app/modules/catalog/static/store/js/products.js
/**
 * Store products management page logic
 * View, edit, and manage store's product catalog
 */

const storeProductsLog = window.LogConfig.loggers.storeProducts ||
    window.LogConfig.createLogger('storeProducts', false);

storeProductsLog.info('Loading...');

function storeProducts() {
    storeProductsLog.info('storeProducts() called');

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

        // Set page identifier
        currentPage: 'products',

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

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

        // Filters
        filters: {
            search: '',
            status: '',  // 'active', 'inactive', ''
            featured: '' // 'true', 'false', ''
        },

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

        // Modal states
        showDeleteModal: false,
        showDetailModal: false,
        showBulkDeleteModal: false,
        selectedProduct: null,

        // Bulk selection
        selectedProducts: [],

        // 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;
        },

        // Computed: Check if all visible products are selected
        get allSelected() {
            return this.products.length > 0 && this.selectedProducts.length === this.products.length;
        },

        // Computed: Check if some but not all products are selected
        get someSelected() {
            return this.selectedProducts.length > 0 && this.selectedProducts.length < this.products.length;
        },

        async init() {
            try {
                // Load i18n translations
                await I18n.loadModule('catalog');

                storeProductsLog.info('Products init() called');

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

                // IMPORTANT: Call parent init first to set storeCode from URL
                const parentInit = data().init;
                if (parentInit) {
                    await parentInit.call(this);
                }

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

                await this.loadProducts();

                storeProductsLog.info('Products initialization complete');
            } catch (error) {
                storeProductsLog.error('Init failed:', error);
                this.error = 'Failed to initialize products page';
            }
        },

        /**
         * 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.status) {
                    params.append('is_active', this.filters.status === 'active');
                }
                if (this.filters.featured) {
                    params.append('is_featured', this.filters.featured === 'true');
                }

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

                // Calculate stats from response or products
                this.stats = {
                    total: response.total || this.products.length,
                    active: this.products.filter(p => p.is_active).length,
                    inactive: this.products.filter(p => !p.is_active).length,
                    featured: this.products.filter(p => p.is_featured).length
                };

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

        /**
         * Apply filter and reload
         */
        applyFilter() {
            this.pagination.page = 1;
            this.loadProducts();
        },

        /**
         * Clear all filters
         */
        clearFilters() {
            this.filters = {
                search: '',
                status: '',
                featured: ''
            };
            this.pagination.page = 1;
            this.loadProducts();
        },

        /**
         * Toggle product active status
         */
        async toggleActive(product) {
            this.saving = true;
            try {
                await apiClient.put(`/store/products/${product.id}/toggle-active`);
                product.is_active = !product.is_active;
                Utils.showToast(
                    product.is_active ? I18n.t('catalog.messages.product_activated') : I18n.t('catalog.messages.product_deactivated'),
                    'success'
                );
                storeProductsLog.info('Toggled product active:', product.id, product.is_active);
            } catch (error) {
                storeProductsLog.error('Failed to toggle active:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_update_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Toggle product featured status
         */
        async toggleFeatured(product) {
            this.saving = true;
            try {
                await apiClient.put(`/store/products/${product.id}/toggle-featured`);
                product.is_featured = !product.is_featured;
                Utils.showToast(
                    product.is_featured ? I18n.t('catalog.messages.product_marked_as_featured') : I18n.t('catalog.messages.product_unmarked_as_featured'),
                    'success'
                );
                storeProductsLog.info('Toggled product featured:', product.id, product.is_featured);
            } catch (error) {
                storeProductsLog.error('Failed to toggle featured:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_update_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * View product details
         */
        viewProduct(product) {
            this.selectedProduct = product;
            this.showDetailModal = true;
        },

        /**
         * Confirm delete product
         */
        confirmDelete(product) {
            this.selectedProduct = product;
            this.showDeleteModal = true;
        },

        /**
         * Execute delete product
         */
        async deleteProduct() {
            if (!this.selectedProduct) return;

            this.saving = true;
            try {
                await apiClient.delete(`/store/products/${this.selectedProduct.id}`);
                Utils.showToast(I18n.t('catalog.messages.product_deleted_successfully'), 'success');
                storeProductsLog.info('Deleted product:', this.selectedProduct.id);

                this.showDeleteModal = false;
                this.selectedProduct = null;
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Failed to delete product:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_delete_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Navigate to edit product page
         */
        editProduct(product) {
            window.location.href = `/store/${this.storeCode}/products/${product.id}/edit`;
        },

        /**
         * Navigate to create product page
         */
        createProduct() {
            window.location.href = `/store/${this.storeCode}/products/create`;
        },

        /**
         * Format price for display
         */
        formatPrice(cents) {
            if (!cents && cents !== 0) return '-';
            const locale = window.STORE_CONFIG?.locale || 'en-GB';
            const currency = window.STORE_CONFIG?.currency || 'EUR';
            return new Intl.NumberFormat(locale, {
                style: 'currency',
                currency: currency
            }).format(cents / 100);
        },

        /**
         * 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();
            }
        },

        // ============================================================================
        // BULK OPERATIONS
        // ============================================================================

        /**
         * Toggle select all products on current page
         */
        toggleSelectAll() {
            if (this.allSelected) {
                this.selectedProducts = [];
            } else {
                this.selectedProducts = this.products.map(p => p.id);
            }
        },

        /**
         * Toggle selection of a single product
         */
        toggleSelect(productId) {
            const index = this.selectedProducts.indexOf(productId);
            if (index === -1) {
                this.selectedProducts.push(productId);
            } else {
                this.selectedProducts.splice(index, 1);
            }
        },

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

        /**
         * Clear all selections
         */
        clearSelection() {
            this.selectedProducts = [];
        },

        /**
         * Bulk activate selected products
         */
        async bulkActivate() {
            if (this.selectedProducts.length === 0) return;

            this.saving = true;
            try {
                let successCount = 0;
                for (const productId of this.selectedProducts) {
                    const product = this.products.find(p => p.id === productId);
                    if (product && !product.is_active) {
                        await apiClient.put(`/store/products/${productId}/toggle-active`);
                        product.is_active = true;
                        successCount++;
                    }
                }
                Utils.showToast(I18n.t('catalog.messages.products_activated', { count: successCount }), 'success');
                this.clearSelection();
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Bulk activate failed:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_activate_products'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Bulk deactivate selected products
         */
        async bulkDeactivate() {
            if (this.selectedProducts.length === 0) return;

            this.saving = true;
            try {
                let successCount = 0;
                for (const productId of this.selectedProducts) {
                    const product = this.products.find(p => p.id === productId);
                    if (product && product.is_active) {
                        await apiClient.put(`/store/products/${productId}/toggle-active`);
                        product.is_active = false;
                        successCount++;
                    }
                }
                Utils.showToast(I18n.t('catalog.messages.products_deactivated', { count: successCount }), 'success');
                this.clearSelection();
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Bulk deactivate failed:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_deactivate_products'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Bulk set featured on selected products
         */
        async bulkSetFeatured() {
            if (this.selectedProducts.length === 0) return;

            this.saving = true;
            try {
                let successCount = 0;
                for (const productId of this.selectedProducts) {
                    const product = this.products.find(p => p.id === productId);
                    if (product && !product.is_featured) {
                        await apiClient.put(`/store/products/${productId}/toggle-featured`);
                        product.is_featured = true;
                        successCount++;
                    }
                }
                Utils.showToast(I18n.t('catalog.messages.products_marked_as_featured', { count: successCount }), 'success');
                this.clearSelection();
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Bulk set featured failed:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_update_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Bulk remove featured from selected products
         */
        async bulkRemoveFeatured() {
            if (this.selectedProducts.length === 0) return;

            this.saving = true;
            try {
                let successCount = 0;
                for (const productId of this.selectedProducts) {
                    const product = this.products.find(p => p.id === productId);
                    if (product && product.is_featured) {
                        await apiClient.put(`/store/products/${productId}/toggle-featured`);
                        product.is_featured = false;
                        successCount++;
                    }
                }
                Utils.showToast(I18n.t('catalog.messages.products_unmarked_as_featured', { count: successCount }), 'success');
                this.clearSelection();
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Bulk remove featured failed:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_update_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        /**
         * Confirm bulk delete
         */
        confirmBulkDelete() {
            if (this.selectedProducts.length === 0) return;
            this.showBulkDeleteModal = true;
        },

        /**
         * Execute bulk delete
         */
        async bulkDelete() {
            if (this.selectedProducts.length === 0) return;

            this.saving = true;
            try {
                let successCount = 0;
                for (const productId of this.selectedProducts) {
                    await apiClient.delete(`/store/products/${productId}`);
                    successCount++;
                }
                Utils.showToast(I18n.t('catalog.messages.products_deleted', { count: successCount }), 'success');
                this.showBulkDeleteModal = false;
                this.clearSelection();
                await this.loadProducts();
            } catch (error) {
                storeProductsLog.error('Bulk delete failed:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_delete_product'), 'error');
            } finally {
                this.saving = false;
            }
        }
    };
}
