// static/admin/js/vendor-edit.js

// ✅ Use centralized logger - ONE LINE!
// Create custom logger for vendor edit
const editLog = window.LogConfig.createLogger('VENDOR-EDIT');

function adminVendorEdit() {
    return {
        // Inherit base layout functionality from init-alpine.js
        ...data(),

        // Vendor edit page specific state
        currentPage: 'vendor-edit',
        loading: false,
        vendor: null,
        formData: {},
        errors: {},
        loadingVendor: false,
        saving: false,
        vendorCode: null,

        // Initialize
        async init() {
            // Load i18n translations
            await I18n.loadModule('tenancy');

            editLog.info('=== VENDOR EDIT PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._vendorEditInitialized) {
                editLog.warn('Vendor edit page already initialized, skipping...');
                return;
            }
            window._vendorEditInitialized = true;

            try {
                // Get vendor code from URL
                const path = window.location.pathname;
                const match = path.match(/\/admin\/vendors\/([^\/]+)\/edit/);

                if (match) {
                    this.vendorCode = match[1];
                    editLog.info('Editing vendor:', this.vendorCode);
                    await this.loadVendor();
                } else {
                    editLog.error('No vendor code in URL');
                    Utils.showToast(I18n.t('tenancy.messages.invalid_vendor_url'), 'error');
                    setTimeout(() => window.location.href = '/admin/vendors', 2000);
                }

                editLog.info('=== VENDOR EDIT PAGE INITIALIZATION COMPLETE ===');
            } catch (error) {
                window.LogConfig.logError(error, 'Vendor Edit Init');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_initialize_page'), 'error');
            }
        },

        // Load vendor data
        async loadVendor() {
            editLog.info('Loading vendor data...');
            this.loadingVendor = true;

            try {
                const url = `/admin/vendors/${this.vendorCode}`;
                window.LogConfig.logApiCall('GET', url, null, 'request');

                const startTime = performance.now();
                const response = await apiClient.get(url);
                const duration = performance.now() - startTime;

                window.LogConfig.logApiCall('GET', url, response, 'response');
                window.LogConfig.logPerformance('Load Vendor', duration);

                this.vendor = response;

                // Initialize form data
                // For contact fields: empty if inherited (shows placeholder), actual value if override
                this.formData = {
                    name: response.name || '',
                    subdomain: response.subdomain || '',
                    description: response.description || '',
                    // Contact fields: empty string for inherited (will show company value as placeholder)
                    contact_email: response.contact_email_inherited ? '' : (response.contact_email || ''),
                    contact_phone: response.contact_phone_inherited ? '' : (response.contact_phone || ''),
                    website: response.website_inherited ? '' : (response.website || ''),
                    business_address: response.business_address_inherited ? '' : (response.business_address || ''),
                    tax_number: response.tax_number_inherited ? '' : (response.tax_number || ''),
                    // Marketplace URLs (no inheritance)
                    letzshop_csv_url_fr: response.letzshop_csv_url_fr || '',
                    letzshop_csv_url_en: response.letzshop_csv_url_en || '',
                    letzshop_csv_url_de: response.letzshop_csv_url_de || ''
                };

                editLog.info(`Vendor loaded in ${duration}ms`, {
                    vendor_code: this.vendor.vendor_code,
                    name: this.vendor.name
                });
                editLog.debug('Form data initialized:', this.formData);

            } catch (error) {
                window.LogConfig.logError(error, 'Load Vendor');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_load_vendor'), 'error');
                setTimeout(() => window.location.href = '/admin/vendors', 2000);
            } finally {
                this.loadingVendor = false;
            }
        },

        // Format subdomain
        formatSubdomain() {
            this.formData.subdomain = this.formData.subdomain
                .toLowerCase()
                .replace(/[^a-z0-9-]/g, '');
            editLog.debug('Subdomain formatted:', this.formData.subdomain);
        },

        // Submit form
        async handleSubmit() {
            editLog.info('=== SUBMITTING VENDOR UPDATE ===');
            editLog.debug('Form data:', this.formData);

            this.errors = {};
            this.saving = true;

            try {
                const url = `/admin/vendors/${this.vendorCode}`;
                window.LogConfig.logApiCall('PUT', url, this.formData, 'request');

                const startTime = performance.now();
                const response = await apiClient.put(url, this.formData);
                const duration = performance.now() - startTime;

                window.LogConfig.logApiCall('PUT', url, response, 'response');
                window.LogConfig.logPerformance('Update Vendor', duration);

                this.vendor = response;
                Utils.showToast(I18n.t('tenancy.messages.vendor_updated_successfully'), 'success');
                editLog.info(`Vendor updated successfully in ${duration}ms`, response);

                // Optionally redirect back to list
                // setTimeout(() => window.location.href = '/admin/vendors', 1500);

            } catch (error) {
                window.LogConfig.logError(error, 'Update Vendor');

                // Handle validation errors
                if (error.details && error.details.validation_errors) {
                    error.details.validation_errors.forEach(err => {
                        const field = err.loc?.[1] || err.loc?.[0];
                        if (field) {
                            this.errors[field] = err.msg;
                        }
                    });
                    editLog.debug('Validation errors:', this.errors);
                }

                Utils.showToast(error.message || 'Failed to update vendor', 'error');
            } finally {
                this.saving = false;
                editLog.info('=== VENDOR UPDATE COMPLETE ===');
            }
        },

        // Toggle verification
        async toggleVerification() {
            const action = this.vendor.is_verified ? 'unverify' : 'verify';
            editLog.info(`Toggle verification: ${action}`);

            if (!confirm(`Are you sure you want to ${action} this vendor?`)) {
                editLog.info('Verification toggle cancelled by user');
                return;
            }

            this.saving = true;
            try {
                const url = `/admin/vendors/${this.vendorCode}/verification`;
                const payload = { is_verified: !this.vendor.is_verified };

                window.LogConfig.logApiCall('PUT', url, payload, 'request');

                const response = await apiClient.put(url, payload);

                window.LogConfig.logApiCall('PUT', url, response, 'response');

                this.vendor = response;
                Utils.showToast(`Vendor ${action}ed successfully`, 'success');
                editLog.info(`Vendor ${action}ed successfully`);

            } catch (error) {
                window.LogConfig.logError(error, `Toggle Verification (${action})`);
                Utils.showToast(`Failed to ${action} vendor`, 'error');
            } finally {
                this.saving = false;
            }
        },

        // Toggle active status
        async toggleActive() {
            const action = this.vendor.is_active ? 'deactivate' : 'activate';
            editLog.info(`Toggle active status: ${action}`);

            if (!confirm(`Are you sure you want to ${action} this vendor?\n\nThis will affect their operations.`)) {
                editLog.info('Active status toggle cancelled by user');
                return;
            }

            this.saving = true;
            try {
                const url = `/admin/vendors/${this.vendorCode}/status`;
                const payload = { is_active: !this.vendor.is_active };

                window.LogConfig.logApiCall('PUT', url, payload, 'request');

                const response = await apiClient.put(url, payload);

                window.LogConfig.logApiCall('PUT', url, response, 'response');

                this.vendor = response;
                Utils.showToast(`Vendor ${action}d successfully`, 'success');
                editLog.info(`Vendor ${action}d successfully`);

            } catch (error) {
                window.LogConfig.logError(error, `Toggle Active Status (${action})`);
                Utils.showToast(`Failed to ${action} vendor`, 'error');
            } finally {
                this.saving = false;
            }
        },

        // Delete vendor
        async deleteVendor() {
            editLog.info('Delete vendor requested');

            const vendorName = this.vendor?.name || this.vendorCode;
            if (!confirm(`Are you sure you want to delete "${vendorName}"?\n\n⚠️ WARNING: This will permanently delete:\n• All products\n• All orders\n• All customers\n• All team members\n\nThis action cannot be undone!`)) {
                editLog.info('Delete cancelled by user');
                return;
            }

            // Double confirmation for safety
            if (!confirm(`FINAL CONFIRMATION\n\nType OK to permanently delete "${vendorName}" and ALL associated data.`)) {
                editLog.info('Delete cancelled at final confirmation');
                return;
            }

            this.saving = true;
            try {
                const url = `/admin/vendors/${this.vendorCode}?confirm=true`;
                window.LogConfig.logApiCall('DELETE', url, null, 'request');

                const response = await apiClient.delete(url);

                window.LogConfig.logApiCall('DELETE', url, response, 'response');

                Utils.showToast(I18n.t('tenancy.messages.vendor_deleted_successfully'), 'success');
                editLog.info('Vendor deleted successfully');

                // Redirect to vendors list
                setTimeout(() => {
                    window.location.href = '/admin/vendors';
                }, 1500);

            } catch (error) {
                window.LogConfig.logError(error, 'Delete Vendor');
                Utils.showToast(error.message || 'Failed to delete vendor', 'error');
            } finally {
                this.saving = false;
            }
        },

        // ===== Contact Field Inheritance Methods =====

        /**
         * Reset a single contact field to inherit from company.
         * Sets the field to empty string, which the backend converts to null (inherit).
         * @param {string} fieldName - The contact field to reset
         */
        resetFieldToCompany(fieldName) {
            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            if (!contactFields.includes(fieldName)) {
                editLog.warn('Invalid contact field:', fieldName);
                return;
            }

            editLog.info(`Resetting ${fieldName} to inherit from company`);
            this.formData[fieldName] = '';
        },

        /**
         * Reset all contact fields to inherit from company.
         */
        resetAllContactToCompany() {
            editLog.info('Resetting all contact fields to inherit from company');

            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            contactFields.forEach(field => {
                this.formData[field] = '';
            });

            Utils.showToast(I18n.t('tenancy.messages.all_contact_fields_reset_to_company_defa'), 'info');
        },

        /**
         * Check if any contact field has a value (not empty = has override).
         * @returns {boolean} True if at least one contact field has a value
         */
        hasAnyContactOverride() {
            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            return contactFields.some(field => this.formData[field]);
        }
    };
}

editLog.info('Vendor edit module loaded');