<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Saved Images</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js  "></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        .controls {
            margin-bottom: 20px;
        }

        button {
            padding: 10px 15px;
            margin-right: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .image-preview {
            width: 100px;
            height: auto;
        }

        input[type="checkbox"] {
            transform: scale(1.2);
        }

        #status {
            padding: 10px;
            margin: 10px 0;
            background-color: #f0f0f0;
        }

        a {
            color: #007bff;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        /* Style for position input fields */
        .position-input {
            width: 50px;
            padding: 4px;
            text-align: center;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <h1>Saved Images</h1>
    <p><a href="/">Back to Live Feed</a></p>
    <div id="status">Loading images...</div>
    <div class="controls">
        <button id="refreshBtn">Refresh List</button>
        <button id="exportBtn" disabled>Export Selected</button>
        <button id="deleteSelectedBtn" disabled>Delete Selected</button>
    </div>

    <table id="imagesTable">
        <thead>
            <tr>
                <th>
                    <input type="checkbox" id="selectAllCheckbox">
                    <label for="selectAllCheckbox"
                        style="display: inline-block; margin-left: 5px; cursor: pointer;">Select All</label>
                </th>
                <th>ID</th>
                <th>Left Marked Image</th>
                <th>Right Marked Image</th>
                <th>Timestamp</th>
                <th>Comment</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody id="imagesTableBody">
            <!-- 动态加载行 -->
        </tbody>
    </table>

    <script>
        const socket = io('http://' + document.domain + ':' + location.port);
        let allImages = [];

        async function loadImages() {
            document.getElementById('status').textContent = 'Loading images...';
            try {
                const response = await fetch('/api/images');
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                allImages = await response.json();
                renderTable(allImages);
                document.getElementById('status').textContent = `Loaded ${allImages.length} images.`;
                updateSelectAllCheckbox();
            } catch (error) {
                console.error('Error loading images:', error);
                document.getElementById('status').textContent = 'Error loading images: ' + error.message;
            }
        }

        function renderTable(images) {
            const tbody = document.getElementById('imagesTableBody');
            tbody.innerHTML = '';

            images.forEach(image => {
                const row = tbody.insertRow();

                // Checkbox column
                row.insertCell(0).innerHTML = `<input type="checkbox" class="selectCheckbox" data-id="${image.id}">`;

                // ID
                row.insertCell(1).textContent = image.id;

                // Left Marked Image
                const leftMarkedCell = row.insertCell(2);
                if (image.left_marked_filename) {
                    const img = document.createElement('img');
                    img.src = `/static/received/left_marked/${image.left_marked_filename}`;
                    img.alt = "Left Marked Image";
                    img.className = 'image-preview';
                    img.onerror = function () {
                        this.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="75" viewBox="0 0 100 75"><rect width="100" height="75" fill="%23eee"/><text x="50" y="40" font-family="Arial" font-size="12" fill="%23999" text-anchor="middle">No Image</text></svg>';
                    };
                    leftMarkedCell.appendChild(img);
                } else {
                    leftMarkedCell.textContent = "N/A";
                }

                // Right Marked Image
                const rightMarkedCell = row.insertCell(3);
                if (image.right_marked_filename) {
                    const img = document.createElement('img');
                    img.src = `/static/received/right_marked/${image.right_marked_filename}`;
                    img.alt = "Right Marked Image";
                    img.className = 'image-preview';
                    img.onerror = function () {
                        this.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="75" viewBox="0 0 100 75"><rect width="100" height="75" fill="%23eee"/><text x="50" y="40" font-family="Arial" font-size="12" fill="%23999" text-anchor="middle">No Image</text></svg>';
                    };
                    rightMarkedCell.appendChild(img);
                } else {
                    rightMarkedCell.textContent = "N/A";
                }

                // Timestamp
                row.insertCell(4).textContent = new Date(image.timestamp * 1000).toISOString();

                // Comment
                const commentCell = row.insertCell(5);
                const commentInput = document.createElement('input');
                commentInput.type = 'text';
                commentInput.id = `comment-${image.id}`;
                commentInput.value = image.comment || '';
                commentInput.onchange = function() {
                    updateComment(image.id, this.value);
                };
                commentCell.appendChild(commentInput);

                // Actions
                const actionsCell = row.insertCell(6);

                console.log(image);

                actionsCell.innerHTML = `
                    <button onclick="deleteImage(${image.id})">DEL</button>
                    <button onclick="window.open('/manual-annotation?id=${image.id}&side=left', '_blank')">LBL</button>
                    <button onclick="window.open('/manual-annotation?id=${image.id}&side=right', '_blank')">LBR</button>
                    <!-- Position inputs -->
                    <label>左:</label>
                    <input type="number" id="left-position-${image.id}" class="position-input" value="${image.left_position || 0}" min="0" max="14" onchange="updatePosition(${image.id})">
                    <label>右:</label>
                    <input type="number" id="right-position-${image.id}" class="position-input" value="${image.right_position || 0}" min="0" max="14" onchange="updatePosition(${image.id})">
                `;
            });
        }

        async function updateComment(id, comment) {
            try {
                const response = await fetch('/api/images/comment', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: id, comment: comment })
                });
                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({ error: response.statusText }));
                    throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
                }
                document.getElementById('status').textContent = `Comment for image ID ${id} updated.`;
            } catch (error) {
                console.error('Error updating comment:', error);
                document.getElementById('status').textContent = 'Error updating comment: ' + error.message;
            }
        }

        async function updatePosition(id) {
            const leftInput = document.getElementById(`left-position-${id}`);
            const rightInput = document.getElementById(`right-position-${id}`);
            const leftValue = parseInt(leftInput.value) || 0;
            const rightValue = parseInt(rightInput.value) || 0;

            console.log(`Updating position for image ID ${id}: Left=${leftValue}, Right=${rightValue}`);
            if (leftValue < 0 || leftValue > 14 || rightValue < 0 || rightValue > 14) {
                alert("Position values must be between 0 and 14.");
                loadImages(); // Reload to reset invalid values
                return;
            }

            try {
                const response = await fetch('/api/images/position', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: id, left_position: leftValue, right_position: rightValue })
                });
                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({ error: response.statusText }));
                    throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
                }
                document.getElementById('status').textContent = `Position for image ID ${id} updated.`;
            } catch (error) {
                console.error('Error updating position:', error);
                document.getElementById('status').textContent = 'Error updating position: ' + error.message;
            }
        }

        async function deleteImage(id) {
            if (!confirm(`Are you sure you want to delete image ID ${id}?`)) return;

            try {
                const response = await fetch('/api/images', {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: id })
                });
                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({ error: response.statusText }));
                    throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
                }
                allImages = allImages.filter(img => img.id !== id);
                renderTable(allImages);
                updateSelectAllCheckbox();
                document.getElementById('status').textContent = `Image ID ${id} deleted.`;
            } catch (error) {
                console.error('Error deleting image:', error);
                document.getElementById('status').textContent = 'Error deleting image: ' + error.message;
            }
        }

        function getSelectedIds() {
            const checkboxes = document.querySelectorAll('.selectCheckbox:checked');
            return Array.from(checkboxes).map(cb => parseInt(cb.dataset.id));
        }

        function updateSelectAllCheckbox() {
            const checkboxes = document.querySelectorAll('.selectCheckbox');
            const allSelected = checkboxes.length > 0 && checkboxes.length === document.querySelectorAll('.selectCheckbox:checked').length;
            document.getElementById('selectAllCheckbox').checked = allSelected;
            updateExportDeleteButtons();
        }

        function updateExportDeleteButtons() {
            const selectedCount = getSelectedIds().length;
            document.getElementById('exportBtn').disabled = selectedCount === 0;
            document.getElementById('deleteSelectedBtn').disabled = selectedCount === 0;
        }

        document.getElementById('refreshBtn').addEventListener('click', loadImages);

        document.getElementById('exportBtn').addEventListener('click', async function () {
            const selectedIds = getSelectedIds();
            if (selectedIds.length === 0) {
                alert('Please select at least one image to export.');
                return;
            }

            try {
                const response = await fetch('/api/images/export', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ ids: selectedIds })
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({ error: response.statusText }));
                    throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
                }

                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'exported_images.zip';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            } catch (error) {
                console.error('Error exporting images:', error);
                document.getElementById('status').textContent = 'Error exporting images: ' + error.message;
            }
        });

        document.getElementById('deleteSelectedBtn').addEventListener('click', async function () {
            const selectedIds = getSelectedIds();
            if (selectedIds.length === 0) {
                alert('Please select at least one image to delete.');
                return;
            }
            if (!confirm(`Are you sure you want to delete ${selectedIds.length} selected images?`)) return;

            for (const id of selectedIds) {
                try {
                    const response = await fetch('/api/images', {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: id })
                    });
                    if (!response.ok) {
                        const errorData = await response.json().catch(() => ({ error: response.statusText }));
                        throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
                    }
                } catch (error) {
                    console.error(`Error deleting image ID ${id}:`, error);
                    document.getElementById('status').textContent = `Error deleting image ID ${id}: ${error.message}`;
                    return;
                }
            }
            loadImages();
        });

        document.getElementById('selectAllCheckbox').addEventListener('change', function () {
            const isChecked = this.checked;
            const checkboxes = document.querySelectorAll('.selectCheckbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            updateExportDeleteButtons();
        });

        document.getElementById('imagesTable').addEventListener('change', function (e) {
            if (e.target.classList.contains('selectCheckbox')) {
                updateSelectAllCheckbox();
            }
        });

        loadImages();
    </script>
</body>

</html>