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

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

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

        // User edit page specific state
        currentPage: 'user-edit',
        loading: false,
        user: null,
        formData: {},
        errors: {},
        loadingUser: false,
        saving: false,
        userId: null,
        showToggleStatusModal: false,
        showDeleteModal: false,
        showDeleteFinalModal: false,

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

            userEditLog.info('=== USER EDIT PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._userEditInitialized) {
                userEditLog.warn('User edit page already initialized, skipping...');
                return;
            }
            window._userEditInitialized = true;

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

                if (match) {
                    this.userId = parseInt(match[1], 10);
                    userEditLog.info('Editing user:', this.userId);
                    await this.loadUser();
                } else {
                    userEditLog.error('No user ID in URL');
                    Utils.showToast(I18n.t('tenancy.messages.invalid_user_url'), 'error');
                    setTimeout(() => window.location.href = '/admin/users', 2000);
                }

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

        // Load user data
        async loadUser() {
            userEditLog.info('Loading user data...');
            this.loadingUser = 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 User', duration);

                this.user = response;

                // Initialize form data
                this.formData = {
                    username: response.username || '',
                    email: response.email || '',
                    first_name: response.first_name || '',
                    last_name: response.last_name || '',
                    role: response.role || 'store',
                    is_email_verified: response.is_email_verified || false
                };

                userEditLog.info(`User loaded in ${duration}ms`, {
                    user_id: this.user.id,
                    username: this.user.username
                });
                userEditLog.debug('Form data initialized:', this.formData);

            } catch (error) {
                window.LogConfig.logError(error, 'Load User');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_load_user'), 'error');
                setTimeout(() => window.location.href = '/admin/users', 2000);
            } finally {
                this.loadingUser = false;
            }
        },

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

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

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

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

                this.user = response;
                Utils.showToast(I18n.t('tenancy.messages.user_updated_successfully'), 'success');
                userEditLog.info(`User updated successfully in ${duration}ms`, response);

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

                // 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;
                        }
                    });
                    userEditLog.debug('Validation errors:', this.errors);
                }

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

        // Toggle user status
        async toggleStatus() {
            const action = this.user.is_active ? 'deactivate' : 'activate';
            userEditLog.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.user.is_active = response.is_active;
                Utils.showToast(`User ${action}d successfully`, 'success');
                userEditLog.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() {
            userEditLog.info('First delete confirmation accepted, showing final confirmation');
            this.showDeleteFinalModal = true;
        },

        // Delete user
        async deleteUser() {
            userEditLog.info('=== DELETING USER ===');

            if (this.user.owned_merchants_count > 0) {
                Utils.showToast(`Cannot delete user who owns ${this.user.owned_merchants_count} merchant(ies). Transfer ownership first.`, 'error');
                return;
            }

            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(I18n.t('tenancy.messages.user_deleted_successfully'), 'success');
                userEditLog.info('User deleted successfully');

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

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

userEditLog.info('User edit module loaded');
