// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/users.js

// ✅ Use centralized logger - ONE LINE!
const usersLog = window.LogConfig.loggers.users;

function adminUsers() {
    return {
        // Inherit base layout functionality
        ...data(),

        // Set page identifier
        currentPage: 'users',

        // State
        users: [],
        loading: false,
        error: null,
        showToggleStatusModal: false,
        showDeleteModal: false,
        userToToggle: null,
        userToDelete: null,
        filters: {
            search: '',
            role: '',
            is_active: ''
        },
        stats: {
            total_users: 0,
            active_users: 0,
            inactive_users: 0,
            admin_users: 0
        },
        pagination: {
            page: 1,
            per_page: 20,
            total: 0,
            pages: 0
        },

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

            usersLog.info('=== USERS PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._usersInitialized) {
                usersLog.warn('Users page already initialized, skipping...');
                return;
            }
            window._usersInitialized = true;

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

            await this.loadUsers();
            await this.loadStats();

            usersLog.info('=== USERS PAGE INITIALIZATION COMPLETE ===');
        },

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

        // Computed: Total number of 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: Generate page numbers array with ellipsis
        get pageNumbers() {
            const pages = [];
            const totalPages = this.totalPages;
            const current = this.pagination.page;

            if (totalPages <= 7) {
                // Show all pages if 7 or fewer
                for (let i = 1; i <= totalPages; i++) {
                    pages.push(i);
                }
            } else {
                // Always show first page
                pages.push(1);

                if (current > 3) {
                    pages.push('...');
                }

                // Show pages around current page
                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('...');
                }

                // Always show last page
                pages.push(totalPages);
            }

            return pages;
        },

        // Load users from API
        async loadUsers() {
            usersLog.info('Loading users...');
            this.loading = true;
            this.error = null;

            try {
                const params = new URLSearchParams();
                params.append('page', this.pagination.page);
                params.append('per_page', this.pagination.per_page);

                if (this.filters.search) {
                    params.append('search', this.filters.search);
                }
                if (this.filters.role) {
                    params.append('role', this.filters.role);
                }
                if (this.filters.is_active) {
                    params.append('is_active', this.filters.is_active);
                }

                const url = `/admin/users?${params}`;
                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 Users', duration);

                if (response.items) {
                    this.users = response.items;
                    this.pagination.total = response.total;
                    this.pagination.pages = response.pages;
                    this.pagination.page = response.page;
                    this.pagination.per_page = response.per_page;
                    usersLog.info(`Loaded ${this.users.length} users`);
                }
            } catch (error) {
                window.LogConfig.logError(error, 'Load Users');
                this.error = error.message || 'Failed to load users';
                Utils.showToast(I18n.t('tenancy.messages.failed_to_load_users'), 'error');
            } finally {
                this.loading = false;
            }
        },

        // Load statistics
        async loadStats() {
            usersLog.info('Loading user statistics...');

            try {
                const url = '/admin/users/stats';
                window.LogConfig.logApiCall('GET', url, null, 'request');

                const response = await apiClient.get(url);  // ✅ Fixed: lowercase apiClient

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

                if (response) {
                    this.stats = response;
                    usersLog.debug('Stats loaded:', this.stats);
                }
            } catch (error) {
                window.LogConfig.logError(error, 'Load Stats');
            }
        },

        // Search with debounce
        debouncedSearch() {
            // Clear existing timeout
            if (this._searchTimeout) {
                clearTimeout(this._searchTimeout);
            }
            // Set new timeout
            this._searchTimeout = setTimeout(() => {
                usersLog.info('Search triggered:', this.filters.search);
                this.pagination.page = 1;
                this.loadUsers();
            }, 300);
        },

        // Pagination
        nextPage() {
            if (this.pagination.page < this.pagination.pages) {
                this.pagination.page++;
                usersLog.info('Next page:', this.pagination.page);
                this.loadUsers();
            }
        },

        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                usersLog.info('Previous page:', this.pagination.page);
                this.loadUsers();
            }
        },

        goToPage(pageNum) {
            if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
                this.pagination.page = pageNum;
                usersLog.info('Go to page:', this.pagination.page);
                this.loadUsers();
            }
        },

        // Actions
        viewUser(user) {
            usersLog.info('View user:', user.username);
            window.location.href = `/admin/users/${user.id}`;
        },

        editUser(user) {
            usersLog.info('Edit user:', user.username);
            window.location.href = `/admin/users/${user.id}/edit`;
        },

        async toggleUserStatus(user) {
            const action = user.is_active ? 'deactivate' : 'activate';
            usersLog.info(`Toggle user status: ${action}`, user.username);

            try {
                const url = `/admin/users/${user.id}/status`;
                window.LogConfig.logApiCall('PUT', url, { is_active: !user.is_active }, 'request');

                await apiClient.put(url, {  // ✅ Fixed: lowercase apiClient
                    is_active: !user.is_active
                });

                Utils.showToast(`User ${action}d successfully`, 'success');
                usersLog.info(`User ${action}d successfully`);

                await this.loadUsers();
                await this.loadStats();
            } catch (error) {
                window.LogConfig.logError(error, `Toggle User Status (${action})`);
                Utils.showToast(`Failed to ${action} user`, 'error');
            }
        },

        async deleteUser(user) {
            usersLog.warn('Delete user requested:', user.username);

            try {
                const url = `/admin/users/${user.id}`;
                window.LogConfig.logApiCall('DELETE', url, null, 'request');

                await apiClient.delete(url);  // ✅ Fixed: lowercase apiClient

                Utils.showToast(I18n.t('tenancy.messages.user_deleted_successfully'), 'success');
                usersLog.info('User deleted successfully');

                await this.loadUsers();
                await this.loadStats();
            } catch (error) {
                window.LogConfig.logError(error, 'Delete User');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_delete_user'), 'error');
            }
        },

        openCreateModal() {
            usersLog.info('Open create user modal');
            window.location.href = '/admin/users/create';
        }
    };
}

usersLog.info('Users module loaded');
