document.addEventListener('DOMContentLoaded', function () {
    const tradeInfoModal = document.getElementById('tradeInfoModal');
    const tradeInfoContent = document.getElementById('trade-info-content');
    let currentTradeId = null;
    let initialValues = {};

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

                tradeInfoContent.innerHTML = `
                    <h2 class="title">Trade Info</h2>
                    <div id="info-container">
                    <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 id="photo"src="../photo/${tradeDetails.photo}" alt="Trade Photo" />` : ''}
                    </div>
                `;

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

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

                document.getElementById('edit-trade-button').addEventListener('click', () => {
                    enableEditMode(tradeDetails);
                });
            }

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

    function enableEditMode(tradeDetails) {
        initialValues = { ...tradeDetails };
    
        // Clear inner HTML to prevent duplicate elements or nested tags
        document.getElementById('coin-name').innerHTML = '';
        document.getElementById('coinpair-name').innerHTML = '';
        document.getElementById('direction').innerHTML = '';
        document.getElementById('leverage').innerHTML = '';
        document.getElementById('open-price').innerHTML = '';
        document.getElementById('close-price').innerHTML = '';
        document.getElementById('close-date').innerHTML = '';
    
        // Set input fields for editing each property
        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}">`;
    
        // Construct the entire <select> element as a string and assign it once
        let directionSelectHTML = `
            <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('direction').innerHTML = directionSelectHTML;
    
        // Set other fields
        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}">`;
    
        // Toggle button visibility
        document.getElementById('edit-trade-button').style.display = 'none';
        document.getElementById('save-trade-button').style.display = 'block';
    }
    
    
    async function saveTradeChanges() {
        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.');
                tradeInfoModal.style.display = 'none';

                window.dispatchEvent(new Event('tradeUpdated'));
            } else {
                alert('Error updating trade: ' + result.error);
            }

            document.getElementById('edit-trade-button').style.display = 'block';
            document.getElementById('save-trade-button').style.display = 'none';
        } catch (error) {
            console.error('Error updating trade:', error);
        }
    }

    document.getElementById('save-trade-button').addEventListener('click', saveTradeChanges);

    window.addEventListener('tradeRowClicked', (e) => {
        fetchTradeInfo(e.detail);
    });
});
