/**
 * userActivity.js - User activity modal functionality
 * 
 * This module handles all functionality related to the user activity modal.
 */

import { loadUserActivityData } from './api.js';
import { formatTimeToGMT4, formatDurationHours } from './formatters.js';
import { formatDateForDisplay } from './dateUtils.js';
import { showModalError } from './uiHelpers.js';

// User activity modal elements references
let userActivityModal = null;
let modalUsername = null;
let startDateInput = null;
let endDateInput = null;
let applyDateRangeBtn = null;
let userActivityBody = null;
let modalLoadingSpinner = null;
let modalErrorMessage = null;
let userActivityModalInstance = null;

/**
 * Initialize user activity modal component
 */
export function initializeUserActivityModal() {
    // Get references to all modal elements
    userActivityModal = document.getElementById('userActivityModal');
    modalUsername = document.getElementById('modalUsername');
    startDateInput = document.getElementById('startDate');
    endDateInput = document.getElementById('endDate');
    applyDateRangeBtn = document.getElementById('applyDateRange');
    userActivityBody = document.getElementById('userActivityBody');
    modalLoadingSpinner = document.getElementById('modalLoadingSpinner');
    modalErrorMessage = document.getElementById('modalErrorMessage');
    
    // Check if essential modal elements are found
    if (!userActivityModal || !modalUsername || !startDateInput || !endDateInput || !applyDateRangeBtn || !userActivityBody || !modalLoadingSpinner || !modalErrorMessage) {
        console.error("One or more essential user activity modal UI elements are missing from the DOM.");
        // Optionally, disable functionality that relies on these elements or return early
        return; 
    }
    
    // Initialize date inputs with current date
    const today = new Date().toISOString().split('T')[0];
    startDateInput.value = today;
    endDateInput.value = today;
    
    // Add event listener for Apply Date Range button
    applyDateRangeBtn.addEventListener('click', function() {
        const username = modalUsername.textContent;
        loadActivityData(username);
    });
    
    // Listen for custom event from table manager
    document.addEventListener('user-activity-requested', function(event) {
        const username = event.detail.username;
        showUserActivityModal(username);
    });
}

/**
 * Show user activity modal for a specific user
 * @param {string} username - Username to show activity for
 */
export function showUserActivityModal(username) {
    // if (!userActivityModal) { // This check is likely redundant if initializeUserActivityModal is always called first from dashboard.js
    //     initializeUserActivityModal(); 
    // }
    
    // Ensure critical elements were initialized if the above check is removed or failed previously.
    if (!userActivityModal || !modalUsername || !userActivityBody || !modalErrorMessage) {
        console.error("User activity modal called before essential UI elements were ready or found.");
        // Attempt to show a general error or prevent modal from showing an error state.
        // This might involve a global error display if modal itself can't function.
        alert("Error: Activity modal components not loaded. Please refresh."); // Basic fallback
        return;
    }

    modalUsername.textContent = username;
    userActivityBody.innerHTML = '';
    modalErrorMessage.classList.add('d-none');
    
    // Initialize and show modal with Bootstrap 5
    if (!userActivityModalInstance) {
        userActivityModalInstance = new bootstrap.Modal(userActivityModal);
    }
    userActivityModalInstance.show();
    
    // Load user activity data
    loadActivityData(username);
}

/**
 * Load activity data for a specific user
 * @param {string} username - Username to load data for
 */
export async function loadActivityData(username) {
    modalLoadingSpinner.classList.remove('d-none');
    userActivityBody.innerHTML = '';
    modalErrorMessage.classList.add('d-none');
    
    const startDate = startDateInput.value;
    const endDate = endDateInput.value;
    
    try {
        const activities = await loadUserActivityData(username, startDate, endDate);
        populateUserActivityTable(activities);
    } catch (error) {
        console.error('Error in loadActivityData for user:', username, error);
        showModalError(error.message || 'Failed to retrieve activity details.'); // Simplified message
    } finally {
        modalLoadingSpinner.classList.add('d-none');
    }
}

/**
 * Populate user activity table with data
 * @param {Array} activities - Activity data to display
 */
export function populateUserActivityTable(activities) {
    if (activities.length === 0) {
        userActivityBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No activity found for the selected date range.</td></tr>';
        return;
    }
    
    activities.forEach(activity => {
        const row = document.createElement('tr');
        
        // Format date and times for display
        const date = activity.date ? formatDateForDisplay(activity.date) : 'N/A';
        const startTime = formatTimeToGMT4(activity.start_time);
        const endTime = formatTimeToGMT4(activity.end_time);
        
        row.innerHTML = `
            <td>${date}</td>
            <td>${startTime}</td>
            <td>${endTime}</td>
            <td>${formatDurationHours(activity.duration_hours)}</td>
        `;
        userActivityBody.appendChild(row);
    });
} 