/**
 * filters.js - Filtering and sorting functionality
 * 
 * This module handles all filtering and sorting operations for the dashboard.
 */

import AppState from './state.js';
import { populateTableRows } from './tableManager.js';
import { getUserStateValue, getUserActualState } from './userStates.js';
import { setActiveButton } from './uiHelpers.js';

/**
 * Initialize state filters
 */
export function initializeStateFilters() {
    const stateFilterAll = document.getElementById('stateFilterAll');
    const stateFilterWorking = document.getElementById('stateFilterWorking');
    const stateFilterNotWorking = document.getElementById('stateFilterNotWorking');
    
    if (!stateFilterAll || !stateFilterWorking || !stateFilterNotWorking) {
        console.error("State filter buttons not found in initializeStateFilters.");
        return;
    }

    // State filter event listeners
    stateFilterAll.addEventListener('click', function() {
        setActiveStateFilter('all');
        filterTableByState('all');
    });
    
    stateFilterWorking.addEventListener('click', function() {
        setActiveStateFilter('working');
        filterTableByState('working');
    });
    
    stateFilterNotWorking.addEventListener('click', function() {
        setActiveStateFilter('not_working');
        filterTableByState('not_working');
    });
}

/**
 * Set the active state filter button
 * @param {string} filterType - Filter type ('all', 'working', 'not_working')
 */
export function setActiveStateFilter(filterType) {
    const stateFilterAll = document.getElementById('stateFilterAll');
    const stateFilterWorking = document.getElementById('stateFilterWorking');
    const stateFilterNotWorking = document.getElementById('stateFilterNotWorking');
    
    if (!stateFilterAll || !stateFilterWorking || !stateFilterNotWorking) {
        console.error("State filter buttons not found in setActiveStateFilter.");
        return;
    }
    if (!AppState || typeof AppState.setCurrentStateFilter !== 'function') {
        console.error("AppState.setCurrentStateFilter is not available in setActiveStateFilter.");
        return;
    }

    const buttons = [stateFilterAll, stateFilterWorking, stateFilterNotWorking];
    let activeButtonElement = stateFilterAll;
    
    switch (filterType) {
        case 'working':
            activeButtonElement = stateFilterWorking;
            break;
        case 'not_working':
            activeButtonElement = stateFilterNotWorking;
            break;
    }
    setActiveButton(buttons, activeButtonElement); // Use the helper
    
    AppState.setCurrentStateFilter(filterType);
}

/**
 * Filter the table by user state
 * @param {string} stateFilter - State to filter by ('all', 'working', 'not_working')
 */
export function filterTableByState(stateFilter) {
    const reportBody = document.getElementById('reportBody');
    if (!AppState || typeof AppState.getReportData !== 'function' || typeof AppState.getCurrentSortColumn !== 'function' || typeof AppState.getCurrentSortDirection !== 'function') {
        console.error("AppState or its methods are not available in filterTableByState.");
        if (reportBody) reportBody.innerHTML = '';
        return;
    }

    const reportData = AppState.getReportData();
    
    let filteredData;
    if (stateFilter === 'all') {
        filteredData = Array.isArray(reportData) ? [...reportData] : [];
    } else {
        filteredData = Array.isArray(reportData) ? reportData.filter(entry => {
            const userState = getUserActualState(entry.username);
            return userState === stateFilter;
        }) : [];
    }
    
    let dataToPopulate = filteredData;
    if (AppState.getCurrentSortColumn() && AppState.getCurrentSortDirection()) {
        dataToPopulate = sortReportTable(filteredData);
    }

    populateTableRows(dataToPopulate);
}

/**
 * Initialize sorting headers
 */
export function initializeSortingHeaders() {
    const sortableHeaders = document.querySelectorAll('.sortable');
    
    if (!AppState || typeof AppState.setCurrentSortColumn !== 'function' || typeof AppState.setCurrentSortDirection !== 'function' || typeof AppState.getReportData !== 'function' || typeof AppState.getCurrentStateFilter !== 'function') {
        console.error("AppState or its methods are not available in initializeSortingHeaders.");
        return;
    }

    sortableHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const sortType = this.getAttribute('data-sort');
            const currentDir = this.getAttribute('data-dir');
            
            // Remove sorting indicators from all headers
            sortableHeaders.forEach(h => {
                h.removeAttribute('data-dir');
            });
            
            // Set sort direction - toggle between asc/desc or default to asc
            let newDir;
            if (currentDir === 'asc') {
                newDir = 'desc';
            } else {
                newDir = 'asc';
            }
            
            // Update the header with new direction
            this.setAttribute('data-dir', newDir);
            
            // Update sort state
            AppState.setCurrentSortColumn(sortType);
            AppState.setCurrentSortDirection(newDir);
            
            // Get current data, potentially filtered by active state filter
            let dataToProcess = AppState.getReportData();
            const activeStateFilter = AppState.getCurrentStateFilter();

            if (activeStateFilter && activeStateFilter !== 'all') {
                // Ensure reportData is an array before filtering
                if (Array.isArray(dataToProcess)) {
                    dataToProcess = dataToProcess.filter(entry => {
                        const userState = getUserActualState(entry.username);
                        return userState === activeStateFilter;
                    });
                } else {
                    dataToProcess = []; // Or handle as an error
                }
            }
            
            // Sort the potentially filtered data
            const sortedData = sortReportTable(dataToProcess);
            
            // Populate the table with the sorted data
            if (sortedData) {
                populateTableRows(sortedData);
            }
        });
    });
}

/**
 * Sort the report table data.
 * @param {Array} dataToSort - Data to sort.
 * @returns {Array} - The sorted data array.
 */
export function sortReportTable(dataToSort) {
    if (!AppState || typeof AppState.getCurrentSortColumn !== 'function' || typeof AppState.getCurrentSortDirection !== 'function') {
        console.error("AppState or its methods are not available in sortReportTable.");
        return dataToSort; // Return original data if AppState is not ready
    }
    
    const currentSortColumn = AppState.getCurrentSortColumn();
    const currentSortDirection = AppState.getCurrentSortDirection();
    
    if (!currentSortColumn || !currentSortDirection) {
        return;
    }
    
    // Use provided data or fallback to reportData
    const data = dataToSort || AppState.getReportData();
    
    if (data.length === 0) {
        return;
    }
    
    const sortedData = [...data].sort((a, b) => {
        let comparison = 0;
        
        // Sort based on column type
        switch (currentSortColumn) {
            case 'duration':
                // Convert duration to number for comparison
                const durA = a.real_hours_counted === null ? -1 : a.real_hours_counted;
                const durB = b.real_hours_counted === null ? -1 : b.real_hours_counted;
                comparison = durA - durB;
                break;
                
            case 'login':
                // Sort by login time
                const timeA = a.first_login_time || '';
                const timeB = b.first_login_time || '';
                comparison = timeA.localeCompare(timeB);
                break;
                
            case 'state':
                // Sort by user state
                const stateA = getUserStateValue(a.username);
                const stateB = getUserStateValue(b.username);
                comparison = stateA - stateB;
                break;
        }
        
        // Reverse for descending order
        return currentSortDirection === 'desc' ? -comparison : comparison;
    });
    
    // Update table with sorted data
    // const reportBody = document.getElementById('reportBody');
    // reportBody.innerHTML = '';
    // populateTableRows(sortedData);
    return sortedData; // Return the sorted data array
} 