// tradeHistory.js
import { populateDropdowns } from './get_coin_names.js'; // Import the populateDropdowns function

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

    // Display values on the page
    if (email && profileId && accountName) {
        document.getElementById('email').textContent = email;
        document.getElementById('profile_id').textContent = profileId;
        document.getElementById('account_name').textContent = accountName;
    } else {
        console.error("Data not found in sessionStorage");
    }

    // Populate dropdowns with coin data
    populateDropdowns();  // Call this to populate dropdowns for 'coin' and 'coin-name-filter'

    let currentPage = 1;
    const rowsPerPage = 10;
    let tradeData = [];

    async function fetchTradeHistory() {
        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();
            console.log('Trade Data:', tradeData); // Debug: Check data format
            setupPagination(tradeData);
        } catch (error) {
            console.error('Error fetching trade history:', error);
        }
    }

    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');

        // Show first page of data
        displayPage(currentPage);

        // Disable/Enable buttons based on page count
        prevButton.disabled = currentPage === 1;
        nextButton.disabled = currentPage === totalPages || totalPages === 0;

        // Update page info
        pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;

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

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

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

        // Disable/Enable buttons based on the updated page count
        const prevButton = document.getElementById('prev-page');
        const nextButton = document.getElementById('next-page');
        prevButton.disabled = currentPage === 1;
        nextButton.disabled = currentPage === totalPages || totalPages === 0;
    }
    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 function(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', function() {
                window.dispatchEvent(new CustomEvent('tradeRowClicked', { detail: trade.trade_id }));
            });

            tableBody.appendChild(row);
        });
    }

    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);
                const tradeIndex = tradeData.findIndex(t => t.trade_id === tradeId);
                if (tradeIndex > -1) {
                    tradeData.splice(tradeIndex, 1);
                    displayPage(currentPage);
                    updatePageInfo();
                }
            } else {
                console.error('Error deleting trade:', result.error);
            }
        } catch (error) {
            console.error('Error deleting trade:', error);
        }
    }

    window.addEventListener('tradeUpdated', function() {
        fetchTradeHistory();
    });

    // Get filter and clear button elements
    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');
    const clearCoinNameFilterButton = document.getElementById('clear-coin-name-filter');
    const clearDirectionFilterButton = document.getElementById('clear-direction-filter');
    const clearPercentageFilterButton = document.getElementById('clear-percentage-filter');



    // Open and close the filter modal
    document.getElementById('filter-button').addEventListener('click', () => {
        filterModal.style.display = 'block';
    });

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

    // Apply filter logic
    applyFilterButton.addEventListener('click', () => {
        applyFilters();
        filterModal.style.display = 'none';
    });

    // Clear specific filters
    clearCoinNameFilterButton.addEventListener('click', () => {
        document.getElementById('coin').value = '';
        applyFilters();
    });

    clearDirectionFilterButton.addEventListener('click', () => {
        document.getElementById('direction-filter').value = '';
        applyFilters();
    });

    clearPercentageFilterButton.addEventListener('click', () => {
        document.getElementById('percentage-filter').value = '';
        applyFilters();
    });

    // Clear all filters
    clearAllFiltersButton.addEventListener('click', () => {
        document.getElementById('coin').value = '';
        document.getElementById('direction-filter').value = '';
        document.getElementById('percentage-filter').value = '';
        fetchTradeHistory(); // Reset to unfiltered data
    });

    // Function to apply selected filters
    function applyFilters() {
        const coinName = document.getElementById('coin').value;
        const direction = document.getElementById('direction-filter').value;
        const percentage = document.getElementById('percentage-filter').value;

        fetchFilteredTradeHistory(coinName, direction, percentage);
    }

    // Fetch filtered trade data
    async function fetchFilteredTradeHistory(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(tradeData);
        } catch (error) {
            console.error('Error fetching filtered trade history:', error);
        }
    }

    // Fetch all trade data (without filters)
    async function fetchTradeHistory() {
        try {
            const response = await fetch(`../php/get_trade_history.php?account_name=${accountName}&profile_id=${profileId}`);
            tradeData = await response.json();
            setupPagination(tradeData);
        } catch (error) {
            console.error('Error fetching trade history:', error);
        }
    }

    fetchTradeHistory(); // Load full trade history initially
});

