// Import necessary functions
import { populateDropdowns } from './get_coin_names.js';
 

document.addEventListener('DOMContentLoaded', () => {
    const email = sessionStorage.getItem('email');
    const profileId = sessionStorage.getItem('profile_id');
    const accountName = sessionStorage.getItem('account_name');

    if (email && profileId && accountName) {
        document.getElementById('email').textContent = email;
        document.getElementById('profile_id').textContent = profileId;
        document.getElementById('account_name').textContent = accountName;
    
        populateDropdowns();
    
        // Pass parameters explicitly here
        fetchTradeHistory(accountName, profileId);

        // Filter modal logic
        const filterModal = document.getElementById('filterModal');
        const applyFilterButton = document.getElementById('apply-filter-button');
        const closeFilterButton = document.getElementById('close-filter-button');
        const clearAllFiltersButton = document.getElementById('clear-all-filters-button');

        document.getElementById('filter-button').addEventListener('click', () => {
            filterModal.style.display = 'block';
        });

        closeFilterButton.addEventListener('click', () => {
            filterModal.style.display = 'none';
        });

        applyFilterButton.addEventListener('click', () => {
            applyFilters(accountName, profileId);
            filterModal.style.display = 'none';
        });

        clearAllFiltersButton.addEventListener('click', () => {
            document.getElementById('coin').value = '';
            document.getElementById('direction-filter').value = '';
            document.getElementById('percentage-filter').value = '';
            fetchTradeHistory(accountName, profileId);
        });
    } else {
        console.error("Data not found in sessionStorage");
    }
});


window.addEventListener('updateTable', () => {
    const accountName = sessionStorage.getItem('account_name');
    const profileId = sessionStorage.getItem('profile_id');

    if (accountName && profileId) {
        fetchTradeHistory(accountName, profileId);
    } else {
        console.error('Account name or profile ID not found in sessionStorage.');
    }
});

// Global state
let currentPage = 1;
const rowsPerPage = 10;
let tradeData = [];

/**
 * Fetch full trade history from the server.

 * @param {string} accountName 
 * @param {string} profileId 
 */
async function fetchTradeHistory(accountName, profileId) {
    try {
        const response = await fetch(`../php/get_trade_history.php?account_name=${accountName}&profile_id=${profileId}`);
        if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
        tradeData = await response.json();
        setupPagination(tradeData); // Refresh table with new data
    } catch (error) {
        console.error('Error fetching trade history:', error);
    }
}


/**
 * Display the current page of trade data.
 * @param {number} page 
 */
function displayPage(page) {
    const tableBody = document.getElementById('trade-history-body');
    tableBody.innerHTML = '';

    const start = (page - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    const pageData = tradeData.slice(start, end);

    pageData.forEach((trade) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${trade.coin_name}</td>
            <td>${trade.direction}</td>
            <td>${trade.leverage}X</td>
            <td>${trade.percents}%</td>
            <td>${trade.close_date}</td>
        `;

        const deleteCell = document.createElement('td');
        const deleteButton = document.createElement('button');
        deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
        deleteButton.classList.add('delete-btn');

        deleteButton.addEventListener('click', async (e) => {
            e.stopPropagation();
            if (confirm('Are you sure you want to delete this trade?')) {
                row.remove();
                await deleteTrade(trade.trade_id);
            }
        });

        deleteCell.appendChild(deleteButton);
        row.appendChild(deleteCell);

        row.addEventListener('click', () => {
            window.dispatchEvent(new CustomEvent('tradeRowClicked', { detail: trade.trade_id }));
        });

        tableBody.appendChild(row);
    });
}

/**
 * Delete a specific trade by ID.
 * @param {number} tradeId 
 */
async function deleteTrade(tradeId) {
    try {
        const response = await fetch(`../php/delete_trade.php`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ trade_id: tradeId })
        });

        const result = await response.json();
        if (result.success) {
            alert(result.deleted);
            tradeData = tradeData.filter((trade) => trade.trade_id !== tradeId);
            displayPage(currentPage);
            updatePageInfo();
        } else {
            console.error('Error deleting trade:', result.error);
        }
    } catch (error) {
        console.error('Error deleting trade:', error);
    }
}

/**
 * Set up pagination controls.
 */
function setupPagination() {
    const totalPages = Math.ceil(tradeData.length / rowsPerPage);
    const prevButton = document.getElementById('prev-page');
    const nextButton = document.getElementById('next-page');
    const pageInfo = document.getElementById('page-info');

    // Initial display of page data
    displayPage(currentPage);

    // Update navigation controls
    updatePageInfo();

    // Event listeners for pagination buttons
    prevButton.addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            displayPage(currentPage);
            updatePageInfo();
        }
    });

    nextButton.addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            displayPage(currentPage);
            updatePageInfo();
        }
    });
}

/**
 * Update the pagination info display.
 */
function updatePageInfo() {
    const totalPages = Math.ceil(tradeData.length / rowsPerPage);
    const pageInfo = document.getElementById('page-info');
    pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;

    const prevButton = document.getElementById('prev-page');
    const nextButton = document.getElementById('next-page');
    prevButton.disabled = currentPage === 1;
    nextButton.disabled = currentPage === totalPages || totalPages === 0;
}

/**
 * Apply selected filters to the trade data.
 */
function applyFilters(accountName, profileId) {
    const coinName = document.getElementById('coin').value;
    const direction = document.getElementById('direction-filter').value;
    const percentage = document.getElementById('percentage-filter').value;

    fetchFilteredTradeHistory(accountName, profileId, coinName, direction, percentage);
}

/**
 * Fetch trade history with applied filters.
 * @param {string} accountName 
 * @param {string} profileId 
 * @param {string} coinName 
 * @param {string} direction 
 * @param {string} percentage 
 */
async function fetchFilteredTradeHistory(accountName, profileId, coinName, direction, percentage) {
    try {
        const query = new URLSearchParams({
            account_name: accountName,
            profile_id: profileId,
            coin_name: coinName || '',
            direction: direction || '',
            percentage: percentage || ''
        });

        const response = await fetch(`../php/get_trade_history.php?${query.toString()}`);
        tradeData = await response.json();
        setupPagination();
    } catch (error) {
        console.error('Error fetching filtered trade history:', error);
    }
}

// Initialize the application
