document.addEventListener('DOMContentLoaded', function() {
    const accountName = document.getElementById('account_name').textContent;
    let currentPage = 1;
    const rowsPerPage = 10;
    let tradeData = []; // Store trade data here

    // Select modal and modal content elements
    const tradeInfoModal = document.getElementById('tradeInfoModal');  // Modal element
    const tradeInfoContent = document.getElementById('trade-info-content');  // Modal content element

    async function fetchTradeHistory() {
        try {
            
            const response = await fetch(`../php/get_trade_history.php?account_name=${accountName}`);
            tradeData = await response.json();
            setupPagination(tradeData);  // Assuming you have a setupPagination function
        } catch (error) {
            console.error('Error fetching trade history:', error);
        }
    }
    
    // Add event listener to refresh trade history when a new trade is added
    window.addEventListener('tradeAdded', fetchTradeHistory);


    // Set up pagination
    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 to delete a trade from the backend and update the frontend
    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) {
                console.log('Trade deleted successfully.');

                // Update the frontend without reloading
                // Remove from tradeData array
                const tradeIndex = tradeData.findIndex(t => t.trade_id === tradeId);
                if (tradeIndex > -1) {
                    tradeData.splice(tradeIndex, 1);

                    // Recalculate pagination and update table display
                    displayPage(currentPage);
                    updatePageInfo();
                }
            } else {
                console.error('Error deleting trade:', result.error);
            }
        } catch (error) {
            console.error('Error deleting trade:', error);
        }
    }

    // Function to display a specific page of data
    function displayPage(page) {
        const tableBody = document.getElementById('trade-history-body');
        tableBody.innerHTML = '';  // Clear previous rows

        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;

        const pageData = tradeData.slice(start, end); // Get data for current page

        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>
            `;

            // Create a delete button
            const deleteCell = document.createElement('td');

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

            // Attach event listener to the delete button
            deleteButton.addEventListener('click', async function(e) {
                e.stopPropagation(); // Prevent triggering the row click event

                // Ask for confirmation before deleting
                if (confirm('Are you sure you want to delete this trade?')) {
                    // Remove from frontend
                    row.remove();

                    // Remove from backend and update table
                    await deleteTrade(trade.trade_id);
                }
            });

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

            // Add click event listener to the row for other actions
            row.addEventListener('click', function() {
                fetchTradeInfo(trade.trade_id);  // Show trade details in a modal
            });

            tableBody.appendChild(row);
        });

    }

    // Fetch trade history when the page loads
    fetchTradeHistory();
    
    // Function to fetch trade details and display in the modal

// Fetch trade info as before
async function fetchTradeInfo(tradeId) {
    try {
        const response = await fetch(`../php/get_trade_info.php?trade_id=${tradeId}`);
        const tradeDetails = await response.json();

        if (tradeDetails.error) {
            tradeInfoContent.innerHTML = `<p>${tradeDetails.error}</p>`;
        } else {
            // Fill the modal with the trade details (non-editable view)
            tradeInfoContent.innerHTML = `
                <h2>Trade Info</h2>
                <p><strong>Trade ID:</strong> ${tradeDetails.trade_id}</p>
                <p><strong>Coin Name:</strong> <span id="coin-name">${tradeDetails.coin_name}</span></p>
                <p><strong>Coin Pair:</strong> <span id="coinpair-name">${tradeDetails.coinpair_name}</span></p>
                <p><strong>Direction:</strong> <span id="direction">${tradeDetails.direction}</span></p>
                <p><strong>Leverage:</strong> <span id="leverage">${tradeDetails.leverage}</span></p>
                <p><strong>Open Price:</strong> <span id="open-price">${tradeDetails.open_price}</span></p>
                <p><strong>Close Price:</strong> <span id="close-price">${tradeDetails.close_price}</span></p>
                <p><strong>Percents:</strong> <span id="percents">${tradeDetails.percents}%</span></p>
                <p><strong>Close Date:</strong> <span id="close-date">${tradeDetails.close_date}</span></p>
                ${tradeDetails.photo ? `<img src="../photo/${tradeDetails.photo}" alt="Trade Photo" />` : ''}
            `;

            document.getElementById('close-form-button').addEventListener('click', function() {
                tradeInfoModal.style.display = 'none';
            });

            // Add "Edit" button logic
            document.getElementById('edit-trade-button').addEventListener('click', function() {
                enableEditMode(tradeDetails);
            });

            document.getElementById('save-trade-button').addEventListener('click', function() {
                saveTradeChanges(tradeDetails.trade_id);
            });
        }

        tradeInfoModal.style.display = 'block';
    } catch (error) {
        console.error('Error fetching trade details:', error);
        tradeInfoContent.innerHTML = '<p>Error loading trade details.</p>';
    }
}

function enableEditMode(tradeDetails) {
    document.getElementById('coin-name').innerHTML = `<input type="text" id="edit-coin-name" value="${tradeDetails.coin_name}">`;
    document.getElementById('coinpair-name').innerHTML = `<input type="text" id="edit-coinpair-name" value="${tradeDetails.coinpair_name}">`;
    
    // Replace direction text with a select dropdown
    const directionOptions = `
        <select id="edit-direction">
            <option value="1" ${tradeDetails.direction === 'long' ? 'selected' : ''}>Long</option>
            <option value="2" ${tradeDetails.direction === 'short' ? 'selected' : ''}>Short</option>
        </select>`;
    document.getElementById('direction').innerHTML = directionOptions;

    document.getElementById('leverage').innerHTML = `<input type="number" id="edit-leverage" value="${tradeDetails.leverage}">`;
    document.getElementById('open-price').innerHTML = `<input type="number" id="edit-open-price" value="${tradeDetails.open_price}">`;
    document.getElementById('close-price').innerHTML = `<input type="number" id="edit-close-price" value="${tradeDetails.close_price}">`;
    document.getElementById('percents').innerHTML = `<span>${tradeDetails.percents}%</span>`;  // Read-only for percents

    document.getElementById('edit-trade-button').style.display = 'none';
    document.getElementById('save-trade-button').style.display = 'block';
}

// When saving changes, send the selected direction_id instead of direction text
async function saveTradeChanges(tradeId) {
    const updatedTradeData = {
        trade_id: tradeId,
        coin_name: document.getElementById('edit-coin-name').value,
        coinpair_name: document.getElementById('edit-coinpair-name').value,
        direction_id: document.getElementById('edit-direction').value,  // This now holds direction_id (1 or 2)
        leverage: document.getElementById('edit-leverage').value,
        open_price: document.getElementById('edit-open-price').value,
        close_price: document.getElementById('edit-close-price').value
        // Percents will be recalculated on the backend
    };

    try {
        const response = await fetch('../php/update_trade_info.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(updatedTradeData)
        });

        const result = await response.json();
        if (result.success) {
            alert('Trade updated successfully!');
            tradeInfoModal.style.display = 'none';
        } else {
            alert('Error updating trade: ' + result.error);
        }
    } catch (error) {
        console.error('Error updating trade:', error);
    }
}


});
