<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YAML Editor</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .file-list {
            height: 100vh;
            border-right: 1px solid #dee2e6;
            padding: 15px;
            overflow-y: auto;
        }
        .yaml-content {
            height: 100vh;
            padding: 15px;
        }
        .table-container {
            height: calc(100vh - 120px);
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3 file-list">
                <h4>YAML Files</h4>
                <div id="fileList" class="list-group"></div>
            </div>
            <div class="col-md-9 yaml-content">
                <div class="d-flex justify-content-between mb-3">
                    <div class="d-flex gap-2">
                        <button class="btn btn-primary" onclick="addRow()">Add Row</button>
                        <button class="btn btn-danger" onclick="deleteSelectedRow()">Delete Row</button>
                        <button class="btn btn-success" onclick="saveFile()">Save</button>
                    </div>
                    <input type="text" class="form-control w-25" id="searchInput" placeholder="Search..." onkeyup="filterTable()">
                </div>
                <div class="table-container">
                    <table class="table table-bordered table-hover">
                        <thead id="tableHead"></thead>
                        <tbody id="tableBody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentFile = null;
        let yamlData = [];

        async function loadFiles() {
            const response = await fetch('/api/files');
            const data = await response.json();
            const fileList = document.getElementById('fileList');
            fileList.innerHTML = '';
            
            data.files.forEach(file => {
                const item = document.createElement('a');
                item.href = '#';
                item.className = `list-group-item list-group-item-action ${file === currentFile ? 'active' : ''}`;
                item.textContent = file;
                item.onclick = () => loadFile(file);
                fileList.appendChild(item);
            });
        }

        async function loadFile(filePath) {
            document.querySelectorAll('#fileList .list-group-item').forEach(item => {
                item.classList.remove('active');
            });
            currentFile = filePath;
            const response = await fetch(`/api/file/${encodeURIComponent(filePath)}`);
            const data = await response.json();
            yamlData = data.data;
            displayYAMLData(yamlData);
        }

        function displayYAMLData(data) {
            const columns = new Set();
            data.forEach(item => {
                Object.keys(item).forEach(key => columns.add(key));
            });

            const thead = document.getElementById('tableHead');
            const tbody = document.getElementById('tableBody');
            const sortedColumns = Array.from(columns).sort();

            thead.innerHTML = `
                <tr>
                    ${sortedColumns.map(col => `<th>${col}</th>`).join('')}
                </tr>
            `;

            tbody.innerHTML = data.map(item => `
                <tr onclick="selectRow(this)">
                    ${sortedColumns.map(col => `
                        <td contenteditable="true">${item[col] || ''}</td>
                    `).join('')}
                </tr>
            `).join('');
        }
        

        function getTableData() {
            const thead = document.getElementById('tableHead');
            const tbody = document.getElementById('tableBody');
            const columns = Array.from(thead.querySelectorAll('th')).map(th => th.textContent);
            
            return Array.from(tbody.querySelectorAll('tr')).map(row => {
                const rowData = {};
                row.querySelectorAll('td').forEach((cell, index) => {
                    rowData[columns[index]] = cell.textContent;
                });
                return rowData;
            });
        }

        async function saveFile() {
            if (!currentFile) return;
            
            const data = getTableData();
            const response = await fetch(`/api/file/${encodeURIComponent(currentFile)}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ data })
            });

            if (response.ok) {
                alert('File saved successfully');
            } else {
                alert('Error saving file');
            }
        }

        function addRow() {
            const thead = document.getElementById('tableHead');
            const tbody = document.getElementById('tableBody');
            const columns = thead.querySelectorAll('th').length;
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `${'<td contenteditable="true"></td>'.repeat(columns)}`;
            tbody.appendChild(newRow);
        }

        let selectedRow = null;

        function selectRow(row) {
            if (selectedRow) {
                selectedRow.classList.remove('table-active');
            }
            selectedRow = row;
            selectedRow.classList.add('table-active');
        }

        function deleteSelectedRow() {
            if (selectedRow) {
                selectedRow.remove();
                selectedRow = null;
            }
        }

        function filterTable() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const rows = document.querySelectorAll('#tableBody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchText) ? '' : 'none';
            });
        }

        // Load files when page loads
        loadFiles();
    </script>
</body>
</html>