document.addEventListener('DOMContentLoaded', function () {
    const tradeInfoModal = document.getElementById('tradeInfoModal');
    const tradeInfoContent = document.getElementById('trade-info-content');
    const closeInfoButton = document.getElementById('close-info-button');
    const editTradeButton = document.getElementById('edit-trade-button');
    const saveTradeButton = document.getElementById('save-trade-button');
    let currentTradeId = null;
    let initialValues = {};
    let currentTradeDetails = null; // Store current trade details globally

    // Cleanup all listeners
    function cleanupListeners() {
        console.log("Cleaning up listeners");
        closeInfoButton.removeEventListener('click', closeModal);
        editTradeButton.removeEventListener('click', handleEditClick);
        saveTradeButton.removeEventListener('click', saveTradeChanges);
    }

    // Close modal
    function closeModal() {
        console.log("Closing modal and cleaning listeners");
        cleanupListeners();
        tradeInfoModal.style.display = 'none';
    }

    // Fetch trade info and set up modal
    async function fetchTradeInfo(tradeId) {
        currentTradeId = 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 {
                tradeDetails.open_price = parseFloat(tradeDetails.open_price).toString();
                tradeDetails.close_price = parseFloat(tradeDetails.close_price).toString();
    
                currentTradeDetails = tradeDetails; // Store current trade details globally
    
                // Update only the content inside the #trade-info-content
                tradeInfoContent.innerHTML = `
                    <div id="info-container">
                        <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 id="photo" src="../photo/${tradeDetails.photo}" alt="Trade Photo" />` : ''}
                    </div>
                `;
    
                // Make sure buttons are visible as needed
                editTradeButton.style.display = 'block';
                saveTradeButton.style.display = 'none';
    
                cleanupListeners();
    
                // Add listeners
                closeInfoButton.addEventListener('click', closeModal);
                editTradeButton.addEventListener('click', handleEditClick); // No more anonymous function
            }
    
            tradeInfoModal.style.display = 'block';
        } catch (error) {
            console.error('Error fetching trade details:', error);
            tradeInfoContent.innerHTML = '<p>Error loading trade details.</p>';
        }
    }

    // Edit button handler
    function handleEditClick() {
        console.log("Edit button clicked"); // Debugging log
        enableEditMode(currentTradeDetails);

        // Ensure save button has only one listener
        saveTradeButton.removeEventListener('click', saveTradeChanges);
        saveTradeButton.addEventListener('click', saveTradeChanges);
    }

    // Enable edit mode
    function enableEditMode(tradeDetails) {
        initialValues = { ...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}">`;
        document.getElementById('direction').innerHTML = `
            <select id="edit-direction">
                <option value="1" ${(tradeDetails.direction === '1' || tradeDetails.direction === 'Long') ? 'selected' : ''}>Long</option>
                <option value="2" ${(tradeDetails.direction === '2' || tradeDetails.direction === 'Short') ? 'selected' : ''}>Short</option>
            </select>
        `;
        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('close-date').innerHTML = `<input type="date" id="edit-close-date" value="${tradeDetails.close_date}">`;

        editTradeButton.style.display = 'none';
        saveTradeButton.style.display = 'block';
    }

    // Save changes
    async function saveTradeChanges() {
        console.log("Save button clicked"); // Debugging log
        const updatedTradeData = {};
        const updatedFields = {
            coin_name: document.getElementById('edit-coin-name').value,
            coinpair_name: document.getElementById('edit-coinpair-name').value,
            direction: document.getElementById('edit-direction').value,
            leverage: document.getElementById('edit-leverage').value,
            open_price: parseFloat(document.getElementById('edit-open-price').value).toString(),
            close_price: parseFloat(document.getElementById('edit-close-price').value).toString(),
            close_date: document.getElementById('edit-close-date').value,
        };

        for (const [key, value] of Object.entries(updatedFields)) {
            if (value !== initialValues[key]) {
                updatedTradeData[key] = value;
            }
        }
        updatedTradeData.trade_id = currentTradeId;

        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.');
                closeModal();
                window.dispatchEvent(new Event('updateTable'));
            } else {
                alert('Error updating trade: ' + result.error);
            }
        } catch (error) {
            console.error('Error updating trade:', error);
        }
    }

    // Listen for trade row clicks
    window.addEventListener('tradeRowClicked', (e) => {
        console.log("Trade row clicked, fetching trade info");
        fetchTradeInfo(e.detail);
    });
});
