// static/admin/js/merchant-user-edit.js

// Create custom logger for merchant user edit
const merchantUserEditLog = window.LogConfig.createLogger('MERCHANT-USER-EDIT');

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

        // Merchant user edit page specific state
        currentPage: 'merchant-users',
        loading: false,
        merchantUser: null,
        errors: {},
        saving: false,
        userId: null,

        // Editable profile form
        editForm: {
            username: '',
            email: '',
            first_name: '',
            last_name: ''
        },

        // Confirmation modal state
        showToggleStatusModal: false,
        showDeleteModal: false,
        showDeleteFinalModal: false,

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

                merchantUserEditLog.info('=== MERCHANT USER EDIT PAGE INITIALIZING ===');

                // Prevent multiple initializations
                if (window._merchantUserEditInitialized) {
                    merchantUserEditLog.warn('Merchant user edit page already initialized, skipping...');
                    return;
                }
                window._merchantUserEditInitialized = true;

                // Get user ID from URL
                const path = window.location.pathname;
                const match = path.match(/\/admin\/merchant-users\/(\d+)\/edit/);

                if (match) {
                    this.userId = parseInt(match[1], 10);
                    merchantUserEditLog.info('Editing merchant user:', this.userId);
                    await this.loadMerchantUser();
                } else {
                    merchantUserEditLog.error('No user ID in URL');
                    Utils.showToast('Invalid merchant user URL', 'error');
                    setTimeout(() => window.location.href = '/admin/merchant-users', 2000);
                }

                merchantUserEditLog.info('=== MERCHANT USER EDIT PAGE INITIALIZATION COMPLETE ===');
            } catch (error) {
                merchantUserEditLog.error('Init failed:', error);
                this.error = 'Failed to initialize merchant user edit page';
            }
        },

        // Load merchant user data
        async loadMerchantUser() {
            merchantUserEditLog.info('Loading merchant user data...');
            this.loading = true;

            try {
                const url = `/admin/users/${this.userId}`;
                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 Merchant User', duration);

                // Transform API response
                this.merchantUser = {
                    ...response,
                    full_name: [response.first_name, response.last_name].filter(Boolean).join(' ') || null
                };

                // Populate editable form
                this.editForm = {
                    username: this.merchantUser.username || '',
                    email: this.merchantUser.email || '',
                    first_name: this.merchantUser.first_name || '',
                    last_name: this.merchantUser.last_name || ''
                };

                merchantUserEditLog.info(`Merchant user loaded in ${duration}ms`, {
                    id: this.merchantUser.id,
                    username: this.merchantUser.username,
                    role: this.merchantUser.role
                });

            } catch (error) {
                window.LogConfig.logError(error, 'Load Merchant User');
                Utils.showToast('Failed to load merchant user', 'error');
                setTimeout(() => window.location.href = '/admin/merchant-users', 2000);
            } finally {
                this.loading = false;
            }
        },

        // Format date
        formatDate(dateString) {
            if (!dateString) {
                return '-';
            }
            return Utils.formatDate(dateString);
        },

        // Check if profile form has unsaved changes
        get profileDirty() {
            if (!this.merchantUser) return false;
            return this.editForm.username !== (this.merchantUser.username || '') ||
                   this.editForm.email !== (this.merchantUser.email || '') ||
                   this.editForm.first_name !== (this.merchantUser.first_name || '') ||
                   this.editForm.last_name !== (this.merchantUser.last_name || '');
        },

        // Save profile changes
        async saveProfile() {
            merchantUserEditLog.info('Saving profile changes...');
            this.errors = {};

            // Build update payload with only changed fields
            const payload = {};
            if (this.editForm.username !== (this.merchantUser.username || '')) {
                payload.username = this.editForm.username;
            }
            if (this.editForm.email !== (this.merchantUser.email || '')) {
                payload.email = this.editForm.email;
            }
            if (this.editForm.first_name !== (this.merchantUser.first_name || '')) {
                payload.first_name = this.editForm.first_name;
            }
            if (this.editForm.last_name !== (this.merchantUser.last_name || '')) {
                payload.last_name = this.editForm.last_name;
            }

            if (Object.keys(payload).length === 0) return;

            this.saving = true;
            try {
                const url = `/admin/users/${this.userId}`;
                window.LogConfig.logApiCall('PUT', url, payload, 'request');

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

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

                // Update local state
                this.merchantUser.username = response.username;
                this.merchantUser.email = response.email;
                this.merchantUser.first_name = response.first_name;
                this.merchantUser.last_name = response.last_name;
                this.merchantUser.full_name = [response.first_name, response.last_name].filter(Boolean).join(' ') || null;

                // Re-sync form
                this.editForm = {
                    username: response.username || '',
                    email: response.email || '',
                    first_name: response.first_name || '',
                    last_name: response.last_name || ''
                };

                Utils.showToast('Profile updated successfully', 'success');
                merchantUserEditLog.info('Profile updated successfully');

            } catch (error) {
                window.LogConfig.logError(error, 'Save Profile');
                if (error.details) {
                    for (const detail of error.details) {
                        const field = detail.loc?.[detail.loc.length - 1];
                        if (field) this.errors[field] = detail.msg;
                    }
                }
                Utils.showToast(error.message || 'Failed to save profile', 'error');
            } finally {
                this.saving = false;
            }
        },

        // Toggle user status
        async toggleStatus() {
            const action = this.merchantUser.is_active ? 'deactivate' : 'activate';
            merchantUserEditLog.info(`Toggle status: ${action}`);

            this.saving = true;
            try {
                const url = `/admin/users/${this.userId}/status`;
                window.LogConfig.logApiCall('PUT', url, null, 'request');

                const response = await apiClient.put(url);

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

                this.merchantUser.is_active = response.is_active;
                Utils.showToast(`User ${action}d successfully`, 'success');
                merchantUserEditLog.info(`User ${action}d successfully`);

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

        // Intermediate step for double-confirm delete
        confirmDeleteStep() {
            merchantUserEditLog.info('First delete confirmation accepted, showing final confirmation');
            this.showDeleteFinalModal = true;
        },

        // Delete user
        async deleteUser() {
            merchantUserEditLog.info('Delete user requested:', this.userId);

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

                await apiClient.delete(url);

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

                Utils.showToast('User deleted successfully', 'success');
                merchantUserEditLog.info('User deleted successfully');

                // Redirect to merchant users list
                setTimeout(() => window.location.href = '/admin/merchant-users', 1500);

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

merchantUserEditLog.info('Merchant user edit module loaded');
