// app/modules/catalog/static/admin/js/product-create.js
/**
 * Admin store product create page logic
 * Create new store product entries with translations
 */

const adminStoreProductCreateLog = window.LogConfig.loggers.adminStoreProductCreate ||
    window.LogConfig.createLogger('adminStoreProductCreate', false);

adminStoreProductCreateLog.info('Loading...');

function adminStoreProductCreate() {
    adminStoreProductCreateLog.info('adminStoreProductCreate() called');

    // Default translations structure
    const defaultTranslations = () => ({
        en: { title: '', description: '' },
        fr: { title: '', description: '' },
        de: { title: '', description: '' },
        lu: { title: '', description: '' }
    });

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

        // Include media picker functionality (store ID getter will be bound via loadMediaLibrary override)
        ...mediaPickerMixin(() => null, false),

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

        // Loading states
        loading: false,
        saving: false,

        // Tom Select instance
        storeSelectInstance: null,

        // Active language tab
        activeLanguage: 'en',

        // Form data
        form: {
            store_id: null,
            // Translations by language
            translations: defaultTranslations(),
            // Product identifiers
            store_sku: '',
            brand: '',
            gtin: '',
            gtin_type: '',
            // Pricing
            price: null,
            sale_price: null,
            currency: 'EUR',
            tax_rate_percent: 17,
            availability: '',
            // Images
            primary_image_url: '',
            additional_images: [],
            // Status
            is_active: true,
            is_featured: false,
            is_digital: false
        },

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

                adminStoreProductCreateLog.info('Store Product Create init() called');

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

                // Initialize Tom Select
                this.initStoreSelect();

                adminStoreProductCreateLog.info('Store Product Create initialization complete');
            } catch (error) {
                adminStoreProductCreateLog.error('Init failed:', error);
                this.error = 'Failed to initialize product create page';
            }
        },

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

            // Wait for Tom Select to be available
            if (typeof TomSelect === 'undefined') {
                adminStoreProductCreateLog.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: 'Search store...',
                load: async (query, callback) => {
                    try {
                        const response = await apiClient.get('/admin/stores', {
                            search: query,
                            limit: 50
                        });
                        callback(response.stores || []);
                    } catch (error) {
                        adminStoreProductCreateLog.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) => {
                    this.form.store_id = value ? parseInt(value) : null;
                }
            });

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

        /**
         * Generate a unique store SKU
         * Format: XXXX_XXXX_XXXX (includes store_id for uniqueness)
         */
        generateSku() {
            const storeId = this.form.store_id || 0;

            // Generate random alphanumeric segments
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            const generateSegment = (length) => {
                let result = '';
                for (let i = 0; i < length; i++) {
                    result += chars.charAt(Math.floor(Math.random() * chars.length));
                }
                return result;
            };

            // First segment includes store ID (padded)
            const storeSegment = storeId.toString().padStart(4, '0').slice(-4);

            // Generate SKU: VID + random + random
            const sku = `${storeSegment}_${generateSegment(4)}_${generateSegment(4)}`;
            this.form.store_sku = sku;

            adminStoreProductCreateLog.info('Generated SKU:', sku);
        },

        /**
         * Create the product
         */
        async createProduct() {
            if (!this.form.store_id) {
                Utils.showToast(I18n.t('catalog.messages.please_select_a_store'), 'error');
                return;
            }

            if (!this.form.translations.en.title?.trim()) {
                Utils.showToast(I18n.t('catalog.messages.please_enter_a_product_title_english'), 'error');
                return;
            }

            this.saving = true;

            try {
                // Build translations object for API (only include non-empty)
                const translations = {};
                for (const lang of ['en', 'fr', 'de', 'lu']) {
                    const t = this.form.translations[lang];
                    if (t.title?.trim() || t.description?.trim()) {
                        translations[lang] = {
                            title: t.title?.trim() || null,
                            description: t.description?.trim() || null
                        };
                    }
                }

                // Build create payload
                const payload = {
                    store_id: this.form.store_id,
                    translations: Object.keys(translations).length > 0 ? translations : null,
                    // Product identifiers
                    brand: this.form.brand?.trim() || null,
                    store_sku: this.form.store_sku?.trim() || null,
                    gtin: this.form.gtin?.trim() || null,
                    gtin_type: this.form.gtin_type || null,
                    // Pricing
                    price: this.form.price !== null && this.form.price !== ''
                        ? parseFloat(this.form.price) : null,
                    sale_price: this.form.sale_price !== null && this.form.sale_price !== ''
                        ? parseFloat(this.form.sale_price) : null,
                    currency: this.form.currency || 'EUR',
                    tax_rate_percent: this.form.tax_rate_percent !== null
                        ? parseInt(this.form.tax_rate_percent) : 17,
                    availability: this.form.availability || null,
                    // Images
                    primary_image_url: this.form.primary_image_url?.trim() || null,
                    additional_images: this.form.additional_images?.length > 0
                        ? this.form.additional_images : null,
                    // Status
                    is_active: this.form.is_active,
                    is_featured: this.form.is_featured,
                    is_digital: this.form.is_digital
                };

                adminStoreProductCreateLog.info('Creating product with payload:', payload);

                const response = await apiClient.post('/admin/store-products', payload);

                adminStoreProductCreateLog.info('Product created:', response.id);

                Utils.showToast(I18n.t('catalog.messages.product_created_successfully'), 'success');

                // Redirect to the new product's detail page
                setTimeout(() => {
                    window.location.href = `/admin/store-products/${response.id}`;
                }, 1000);
            } catch (error) {
                adminStoreProductCreateLog.error('Failed to create product:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_create_product'), 'error');
            } finally {
                this.saving = false;
            }
        },

        // === Media Picker Overrides ===
        // These override the mixin methods to use proper form context

        /**
         * Load media library for the selected store
         */
        async loadMediaLibrary() {
            const storeId = this.form?.store_id;

            if (!storeId) {
                adminStoreProductCreateLog.warn('Media picker: No store ID selected');
                return;
            }

            this.mediaPickerState.loading = true;
            this.mediaPickerState.skip = 0;

            try {
                const params = new URLSearchParams({
                    skip: '0',
                    limit: this.mediaPickerState.limit.toString(),
                    media_type: 'image',
                });

                if (this.mediaPickerState.search) {
                    params.append('search', this.mediaPickerState.search);
                }

                const response = await apiClient.get(
                    `/admin/media/stores/${storeId}?${params.toString()}`
                );

                this.mediaPickerState.media = response.media || [];
                this.mediaPickerState.total = response.total || 0;
            } catch (error) {
                adminStoreProductCreateLog.error('Failed to load media library:', error);
                Utils.showToast(I18n.t('catalog.messages.failed_to_load_media_library'), 'error');
            } finally {
                this.mediaPickerState.loading = false;
            }
        },

        /**
         * Load more media (pagination)
         */
        async loadMoreMedia() {
            const storeId = this.form?.store_id;
            if (!storeId) return;

            this.mediaPickerState.loading = true;
            this.mediaPickerState.skip += this.mediaPickerState.limit;

            try {
                const params = new URLSearchParams({
                    skip: this.mediaPickerState.skip.toString(),
                    limit: this.mediaPickerState.limit.toString(),
                    media_type: 'image',
                });

                if (this.mediaPickerState.search) {
                    params.append('search', this.mediaPickerState.search);
                }

                const response = await apiClient.get(
                    `/admin/media/stores/${storeId}?${params.toString()}`
                );

                this.mediaPickerState.media = [
                    ...this.mediaPickerState.media,
                    ...(response.media || [])
                ];
            } catch (error) {
                adminStoreProductCreateLog.error('Failed to load more media:', error);
            } finally {
                this.mediaPickerState.loading = false;
            }
        },

        /**
         * Upload a new media file
         */
        async uploadMediaFile(event) {
            const file = event.target.files?.[0];
            if (!file) return;

            const storeId = this.form?.store_id;

            if (!storeId) {
                Utils.showToast(I18n.t('catalog.messages.please_select_a_store_first'), 'error');
                return;
            }

            if (!file.type.startsWith('image/')) {
                Utils.showToast(I18n.t('catalog.messages.please_select_an_image_file'), 'error');
                return;
            }

            if (file.size > 10 * 1024 * 1024) {
                Utils.showToast(I18n.t('catalog.messages.image_must_be_less_than_10mb'), 'error');
                return;
            }

            this.mediaPickerState.uploading = true;

            try {
                const formData = new FormData();
                formData.append('file', file);

                const response = await apiClient.postFormData(
                    `/admin/media/stores/${storeId}/upload?folder=products`,
                    formData
                );

                if (response.success && response.media) {
                    this.mediaPickerState.media.unshift(response.media);
                    this.mediaPickerState.total++;
                    this.toggleMediaSelection(response.media);
                    Utils.showToast(I18n.t('catalog.messages.image_uploaded_successfully'), 'success');
                }
            } catch (error) {
                adminStoreProductCreateLog.error('Failed to upload image:', error);
                Utils.showToast(error.message || I18n.t('catalog.messages.failed_to_upload_image'), 'error');
            } finally {
                this.mediaPickerState.uploading = false;
                event.target.value = '';
            }
        },

        /**
         * Set main image from media picker
         */
        setMainImage(media) {
            this.form.primary_image_url = media.url;
            adminStoreProductCreateLog.info('Main image set:', media.url);
        },

        /**
         * Add additional images from media picker
         */
        addAdditionalImages(mediaList) {
            const newUrls = mediaList.map(m => m.url);
            this.form.additional_images = [
                ...this.form.additional_images,
                ...newUrls
            ];
            adminStoreProductCreateLog.info('Additional images added:', newUrls);
        },

        /**
         * Remove an additional image by index
         */
        removeAdditionalImage(index) {
            this.form.additional_images.splice(index, 1);
        },

        /**
         * Clear the main image
         */
        clearMainImage() {
            this.form.primary_image_url = '';
        }
    };
}
