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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản lý Sản Phẩm</title>
    <link rel="shortcut icon" href="1.png" type="image/x-icon">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script src="key.js"></script>
    <style>
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #666;
        }

        /* Table styles */
        #productsTable {
            border-collapse: collapse;
        }

        #productsTable th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            border-right: 1px solid #dee2e6;
            padding: 8px;
            font-weight: 600;
            text-align: left;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        #productsTable input:focus,
        #productsTable select:focus {
            outline: none;
            background-color: #f0f7ff;
        }
    </style>
</head>

<body class="bg-gray-50">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white p-6 rounded-lg shadow-xl">
            <div class="flex items-center space-x-3">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <div id="loadingText" class="text-gray-700">Đang xử lý...</div>
            </div>
            <div id="progressContainer" class="mt-4 hidden">
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progressBar" class="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
                        style="width: 0%"></div>
                </div>
                <div id="progressText" class="text-sm text-gray-600 mt-1 text-center">0%</div>
            </div>
        </div>
    </div>

    <!-- Main Container -->
    <div class="mx-auto px-4 py-8">
        <div class="bg-white rounded-lg shadow-lg p-6">
            <!-- Header Section -->
            <div class="flex justify-between items-center mb-6">
                <img src="1.png" alt="" width="50">
                <h1 class="text-2xl font-bold text-gray-800">POAL Quản lý sản phẩm</h1>
                <div class="flex items-center space-x-4">
                    <button hidden id="toggleBatchMode" onclick="toggleBatchMode()"
                        class="px-4 py-2 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors">
                        Chọn nhiều
                    </button>
                    <button id="addNewRow" onclick="addNewRow()"
                        class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        Thêm dòng
                    </button>
                    <button id="saveAll" onclick="saveAllProducts()"
                        class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                        </svg>
                        Lưu tất cả
                    </button>
                </div>
            </div>

            <!-- Import Section -->
            <div class="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <h2 class="text-lg font-semibold mb-3">Import từ Excel</h2>
                <div class="flex items-center gap-4">
                    <div class="flex-1">
                        <label for="excelFile"
                            class="block w-full p-4 border-2 border-dashed border-gray-300 rounded-lg text-center cursor-pointer hover:border-blue-500 transition-colors">
                            <span class="text-gray-600">Kéo thả file Excel hoặc click để chọn file</span>
                            <input type="file" id="excelFile" accept=".xlsx, .xls, .csv" class="hidden"
                                onchange="handleFileSelect(this)" />
                        </label>
                    </div>
                    <button onclick="importExcel()"
                        class="px-6 py-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Import
                    </button>
                </div>
            </div>

            <!-- Products Table -->
            <div class="overflow-x-auto border border-gray-200 rounded-lg">
                <table id="productsTable" class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="checkbox-column px-6 py-3 hidden">
                                <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 rounded"
                                    onchange="toggleAllProducts(this)">
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Mã SP</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Tên sản phẩm</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Hình ảnh</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Đơn vị</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Phân loại</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Quy cách</th>

                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Giá nhập</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Giá bán</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Ghi chú</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Thao tác</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Batch Actions -->
    <div id="batchActions"
        class="hidden fixed bottom-8 left-1/2 transform -translate-x-1/2 bg-white px-6 py-4 rounded-lg shadow-xl flex items-center gap-4">
        <span class="text-gray-600" id="selectedCount">Đã chọn: 0</span>
        <button onclick="deleteBatchProducts()"
            class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            Xóa đã chọn
        </button>
        <button onclick="copyBatchProducts()"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
            Nhân bản
        </button>
    </div>

    <!-- Floating Action Buttons -->
    <div id="floatingButtons" class="fixed bottom-6 right-6 flex flex-col gap-3">
        <button onclick="addNewRow()"
            class="bg-green-600 hover:bg-green-700 text-white rounded-full p-4 shadow-lg transition-all hover:scale-105">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
        </button>
        <button onclick="saveAllProducts()"
            class="bg-blue-600 hover:bg-blue-700 text-white rounded-full p-4 shadow-lg transition-all hover:scale-105">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
            </svg>
        </button>
    </div>

    <script>
        // Constants
        const APP_ID = 'e483be4d-1b20-4805-8bcf-c01013ee853b';
        const ACCESS_KEY = 'V2-PelHU-a4w3r-2mlpo-wI0XW-nZvbo-Y5sLF-XoEn4-wf3Ym';
        const REGION = 'www';
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;
        const IMGBB_API_KEY = '7267d539a8c541130ce4524afdc69ad3';

        // State Management
        const state = {
            lastProductId: 0,
            products: new Map(),
            categories: ['Áo thể thao', 'Áo sơ mi', 'Bộ đồ thể thao', 'Quần thể thao', 'Áo phông', 'Quần jeans', 'Áo thun', 'Quần short', 'Quần jogger', 'Quần tây'],
            units: ['Cái', 'Bộ', 'Chiếc', 'Hộp', 'Cuốn', 'Mét', 'Kg', 'Gram', 'Lít', 'Chai', 'Gói', 'Túi', 'Thùng', 'Tấm', 'Bình'],
            batchMode: false
        };

        // Toast Utilities
        const toast = {
            success(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#4CAF50" },
                }).showToast();
            },
            error(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#f44336" },
                }).showToast();
            },
            warning(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#ff9800" },
                }).showToast();
            },
            info(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#2196F3" },
                }).showToast();
            }
        };

        // Loading Utilities
        const loadingUtils = {
            overlay: null,
            progressBar: null,
            progressText: null,
            progressContainer: null,
            loadingText: null,

            init() {
                this.overlay = document.getElementById('loadingOverlay');
                this.progressBar = document.getElementById('progressBar');
                this.progressText = document.getElementById('progressText');
                this.progressContainer = document.getElementById('progressContainer');
                this.loadingText = document.getElementById('loadingText');
            },

            show(message = 'Đang xử lý...', showProgress = false) {
                if (!this.overlay) this.init();
                this.loadingText.textContent = message;
                this.overlay.classList.remove('hidden');
                if (showProgress) {
                    this.progressContainer.classList.remove('hidden');
                    this.updateProgress(0);
                } else {
                    this.progressContainer.classList.add('hidden');
                }
            },

            hide() {
                if (!this.overlay) this.init();
                this.overlay.classList.add('hidden');
                this.progressContainer.classList.add('hidden');
            },

            updateProgress(percent) {
                if (!this.progressBar) this.init();
                this.progressBar.style.width = `${percent}%`;
                this.progressText.textContent = `${percent}%`;
            }
        };

        // DOM Utilities
        const dom = {
            getProductRow(element) {
                return element.closest('tr');
            },

            getProductId(row) {
                return row.dataset.productId;
            },

            createInput(value, type = 'text') {
                const input = document.createElement('input');
                input.type = type;
                input.value = value || '';
                input.className = 'w-full px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent';
                return input;
            },

            createSelect(value, options = [], placeholder = '') {
                const select = document.createElement('select');
                select.className = 'w-full px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent';
                select.innerHTML = `
            <option value="">${placeholder}</option>
            ${options.map(opt => `
                <option value="${opt}" ${value === opt ? 'selected' : ''}>${opt}</option>
            `).join('')}
        `;
                return select;
            },

            createCategorySelect(value) {
                return this.createSelect(value, state.categories, 'Chọn phân loại');
            },

            createUnitSelect(value) {
                return this.createSelect(value, state.units, 'Chọn đơn vị tính');
            }
        };

        // Event Handlers
        const handlers = {
            async handleImageUpload(event, productId) {
                const file = event.target.files[0];
                if (!file) return;

                const row = document.querySelector(`tr[data-product-id="${productId}"]`);
                const imgPreview = row.querySelector('.image-preview');
                const dropZone = row.querySelector('.drop-zone');

                try {
                    const base64 = await this.fileToBase64(file);
                    imgPreview.src = base64;
                    imgPreview.classList.remove('hidden');
                    dropZone.classList.add('has-image');

                    const product = state.products.get(productId);
                    if (product) {
                        product.imageBase64 = base64;
                        product.image = '';
                        state.products.set(productId, product);
                    }
                } catch (error) {
                    console.error('Error handling image:', error);
                    toast.error('Lỗi khi xử lý ảnh. Vui lòng thử lại.');
                }
            },

            fileToBase64(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = error => reject(error);
                });
            },

            makeEditable(element) {
                if (element.querySelector('input, select')) return;

                const value = element.textContent;
                const row = dom.getProductRow(element);
                const productId = dom.getProductId(row);
                const columnIndex = Array.from(row.cells).indexOf(element);
                const cells = Array.from(row.cells);

                let inputElement;

                if (columnIndex === 4) { // Phân loại
                    inputElement = dom.createCategorySelect(value);
                } else if (columnIndex === 3) { // Đơn vị tính
                    inputElement = dom.createUnitSelect(value);
                } else {
                    inputElement = dom.createInput(value);
                }

                // Add keyboard navigation
                inputElement.addEventListener('keydown', (e) => {
                    if (e.key === 'Enter' || e.key === 'Tab') {
                        e.preventDefault();
                        const direction = e.shiftKey ? -1 : 1;
                        this.navigateToNextCell(row, columnIndex, direction);
                        inputElement.blur();
                    }
                });

                inputElement.addEventListener('blur', () => {
                    this.updateCellValue(inputElement, productId, columnIndex);
                });

                element.textContent = '';
                element.appendChild(inputElement);
                inputElement.focus();
            },

            navigateToNextCell(currentRow, currentIndex, direction) {
                const editableCells = Array.from(currentRow.cells).filter(cell => cell.onclick);
                const currentCellIndex = editableCells.indexOf(currentRow.cells[currentIndex]);

                let nextCell;
                if (direction > 0 && currentCellIndex === editableCells.length - 1) {
                    // Move to next row
                    const nextRow = currentRow.nextElementSibling;
                    if (nextRow) {
                        nextCell = Array.from(nextRow.cells).find(cell => cell.onclick);
                    }
                } else if (direction < 0 && currentCellIndex === 0) {
                    // Move to previous row
                    const prevRow = currentRow.previousElementSibling;
                    if (prevRow) {
                        const editablePrevCells = Array.from(prevRow.cells).filter(cell => cell.onclick);
                        nextCell = editablePrevCells[editablePrevCells.length - 1];
                    }
                } else {
                    nextCell = editableCells[currentCellIndex + direction];
                }

                if (nextCell) nextCell.click();
            },

            updateCellValue(element, productId, columnIndex) {
                const value = element.value;
                const cell = element.parentElement;
                const product = state.products.get(productId);

                if (!product) return;

                switch (columnIndex) {
                    case 1: product.name = value; break;
                    case 3: product.unit = value; break;
                    case 4: product.category = value; break;
                    case 5: product.specification = value; break;
                    case 6: product.note = value; break;
                }

                cell.textContent = value || (columnIndex === 4 ? 'Chọn phân loại' : '');
            }
        };

        // Keyboard Shortcuts
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                addNewRow();
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                saveAllProducts();
            }
        });

        // Drag and Drop Utilities
        function setupDragAndDrop(row) {
            const dropZone = row.querySelector('.drop-zone');

            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, () => {
                    dropZone.classList.add('bg-blue-50');
                });
            });

            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, () => {
                    dropZone.classList.remove('bg-blue-50');
                });
            });

            dropZone.addEventListener('drop', (e) => {
                const file = e.dataTransfer.files[0];
                if (file && file.type.startsWith('image/')) {
                    const productId = dom.getProductId(row);
                    handlers.handleImageUpload({ target: { files: [file] } }, productId);
                }
            });
        }

        async function addNewRow() {
            const tbody = document.querySelector('#productsTable tbody');
            const productId = utils.createUniqueId();
            const productCode = utils.generateProductCode();

            const product = {
                id: productId,
                code: productCode,
                name: '',
                image: '',
                unit: '',
                category: '',
                specification: '',
                purchasePrice: '',
                sellingPrice: '',
                note: ''
            };

            state.products.set(productId, product);

            const row = document.createElement('tr');
            row.dataset.productId = productId;
            row.className = 'hover:bg-gray-50 border-b border-gray-200';

            row.innerHTML = `
        ${state.batchMode ? `
            <td class="border-r border-gray-200 p-0">
                <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 rounded m-2"
                       onchange="updateBatchActionVisibility()">
            </td>
        ` : ''}
        <td class="border-r border-gray-200 p-2 text-sm text-gray-500">${productCode}</td>
        <td class="border-r border-gray-200 p-0">
            <div class="h-full w-full">
                <input type="text" 
                       class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                       value=""
                       placeholder="Nhập tên sản phẩm"
                       onchange="handleInputChange(event, '${productId}', 'name')">
            </div>
        </td>
        <td class="border-r border-gray-200 p-1">
            <div class="drop-zone flex items-center gap-2 rounded border border-dashed border-gray-300 hover:border-blue-500 transition-colors">
                <img class="image-preview w-12 h-12 object-cover rounded hidden" src="" alt="Preview">
                <label class="cursor-pointer flex-1 text-center py-1">
                    <input type="file" 
                           accept="image/*" 
                           class="hidden" 
                           onchange="handlers.handleImageUpload(event, '${productId}')">
                    <span class="text-blue-600 hover:text-blue-700 text-sm">Chọn ảnh</span>
                </label>
            </div>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'unit')">
                <option value="">Đơn vị tính</option>
                ${state.units.map(unit => `<option value="${unit}">${unit}</option>`).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'category')">
                <option value="">Phân loại</option>
                ${state.categories.map(cat => `<option value="${cat}">${cat}</option>`).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập quy cách"
                   onchange="handleInputChange(event, '${productId}', 'specification')">
        </td>
        <td class="border-r border-gray-200 p-0">
    <input type="number" 
           class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
           value="${product.purchasePrice || ''}"
           placeholder="Nhập giá nhập"
           onchange="handleInputChange(event, '${product.id}', 'purchasePrice')">
</td>
<td class="border-r border-gray-200 p-0">
    <input type="number" 
           class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
           value="${product.sellingPrice || ''}"
           placeholder="Nhập giá bán"
           onchange="handleInputChange(event, '${product.id}', 'sellingPrice')">
</td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập ghi chú"
                   onchange="handleInputChange(event, '${productId}', 'note')">
        </td>
        <td class="p-1 text-center">
            <div class="flex items-center justify-center gap-1">
                <button onclick="deleteProduct('${productId}')" 
                        class="text-gray-400 hover:text-red-600 transition-colors p-1"
                        title="Xóa sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </button>
                <button onclick="duplicateProduct('${productId}')" 
                        class="text-gray-400 hover:text-blue-600 transition-colors p-1"
                        title="Nhân bản sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                </button>
            </div>
        </td>
    `;

            tbody.appendChild(row);
            setupDragAndDrop(row);

            // Auto focus vào ô tên sản phẩm
            const nameInput = row.querySelector('input[placeholder="Nhập tên sản phẩm"]');
            if (nameInput) nameInput.focus();
        }

        // Thêm hàm xử lý thay đổi input
        function handleInputChange(event, productId, field) {
            const value = event.target.value;
            const product = state.products.get(productId);
            if (product) {
                product[field] = value;
                state.products.set(productId, product);
            }
        }
        async function saveAllProducts() {
            try {
                loadingUtils.show('Đang xử lý dữ liệu...', true);
                const productsArray = Array.from(state.products.values());

                // Validate data
                const invalidProducts = productsArray.filter(p => !p.name || !p.unit);
                if (invalidProducts.length > 0) {
                    toast.warning('Vui lòng điền đầy đủ tên và đơn vị tính cho tất cả sản phẩm');
                    loadingUtils.hide();
                    return;
                }

                // Calculate total steps
                const productsWithNewImages = productsArray.filter(p => p.imageBase64 && !p.image);
                const totalSteps = productsWithNewImages.length + 2;
                let currentStep = 0;

                // Upload images
                if (productsWithNewImages.length > 0) {
                    toast.info(`Đang xử lý ${productsWithNewImages.length} ảnh...`);

                    const uploadPromises = productsWithNewImages.map((product, index) =>
                        uploadToImgbb(product.imageBase64)
                            .then(url => {
                                product.image = url;
                                delete product.imageBase64;
                                loadingUtils.updateProgress(Math.round((index + 1) / productsWithNewImages.length * 60));
                                return url;
                            })
                            .catch(error => {
                                console.error('Error uploading image:', error);
                                toast.error(`Lỗi khi tải ảnh cho sản phẩm "${product.name}"`);
                                return 'https://i.ibb.co/cYHCSgp/image.png';
                            })
                    );

                    await Promise.all(uploadPromises);
                }

                // Format data
                loadingUtils.updateProgress(80);
                const formattedProducts = productsArray.map(product => ({
                    "TÊN HÀNG": product.name,
                    "ĐƠN VỊ TÍNH": product.unit,
                    "PHÂN LOẠI": product.category,
                    "Quy cách": product.specification,
                    "ĐƠN GIÁ NHẬP": product.purchasePrice,
                    "ĐƠN GIÁ XUẤT": product.sellingPrice,
                    "Ghi chú": product.note,
                    "HÌNH ẢNH": product.image || 'https://i.ibb.co/cYHCSgp/image.png'
                }));

                if (formattedProducts.length === 0) {
                    toast.warning('Không có sản phẩm nào để lưu');
                    loadingUtils.hide();
                    return;
                }

                // Save data
                loadingUtils.updateProgress(90);
                await apiRequest('DMHH', 'Add', { Rows: formattedProducts });

                loadingUtils.updateProgress(100);
                setTimeout(() => {
                    loadingUtils.hide();
                    toast.success('Lưu sản phẩm thành công!');
                    resetAfterSave();
                }, 500);

            } catch (error) {
                loadingUtils.hide();
                console.error('Lỗi khi lưu sản phẩm:', error);
                toast.error('Có lỗi xảy ra khi lưu dữ liệu: ' + error.message);
            }
        }

        const uploadToImgbb = async (base64Image) => {
            const IMGBB_API_KEY = '308f780c13a4248bbefa93729342dd47';
            const base64Data = base64Image.split(',')[1];

            try {
                const formData = new FormData();
                formData.append('image', base64Data);

                const response = await axios.post('https://api.imgbb.com/1/upload', formData, {
                    params: {
                        key: IMGBB_API_KEY,
                    },
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                return response.data.data.url;
            } catch (error) {
                throw new Error('Lỗi khi upload ảnh');
            }
        };
        const apiRequest = async (tableName, action, data, select = {}) => {
            try {
                const response = await fetch(`${API_URL}/${tableName}/Action`, {
                    method: 'POST',
                    headers: {
                        'ApplicationAccessKey': ACCESS_KEY,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        Action: action,
                        Properties: select,
                        ...data
                    })
                });

                if (!response.ok) throw new Error('Network response was not ok');
                return await response.json();
            } catch (error) {
                console.error('API request failed:', error);
                throw error;
            }
        };
        async function importExcel() {
            const input = document.getElementById('excelFile');
            const file = input.files[0];

            if (!file) {
                toast.warning('Vui lòng chọn file Excel');
                return;
            }

            try {
                loadingUtils.show('Đang đọc file Excel...', true);
                loadingUtils.updateProgress(30);

                const data = await readExcelFile(file);
                if (data.length === 0) {
                    toast.warning('File Excel không có dữ liệu');
                    loadingUtils.hide();
                    return;
                }

                let importCount = 0;
                data.forEach((row, index) => {
                    if (row['MÃ HÀNG'] || row['TÊN HÀNG']) {
                        const productId = utils.createUniqueId();
                        const product = {
                            id: productId,
                            code: row['MÃ HÀNG'] || utils.generateProductCode(),
                            name: row['TÊN HÀNG'] || '',
                            unit: row['ĐƠN VỊ TÍNH'] || '',
                            category: row['PHÂN LOẠI'] || '',
                            specification: row['QUY CÁCH'] || '',
                            note: row['GHI CHÚ'] || ''
                        };
                        state.products.set(productId, product);
                        addExistingProduct(product);
                        importCount++;
                    }
                    const progress = Math.min(30 + Math.round((index + 1) / data.length * 70), 100);
                    loadingUtils.updateProgress(progress);
                });

                input.value = '';
                setTimeout(() => {
                    loadingUtils.hide();
                    toast.success(`Đã import ${importCount} sản phẩm`);
                }, 500);

            } catch (error) {
                loadingUtils.hide();
                console.error('Error importing Excel:', error);
                toast.error('Có lỗi xảy ra khi import file Excel');
            }
        }
        // Reset after save function
        function resetAfterSave() {
            // Clear the table
            const tbody = document.querySelector('#productsTable tbody');
            tbody.innerHTML = '';

            // Reset state
            state.products.clear();
            state.lastProductId = 0;

            // Reset batch mode
            if (state.batchMode) {
                toggleBatchMode();
            }

            // Add one empty row
            addNewRow();
        }

        // Duplicate product function
        function duplicateProduct(productId) {
            const originalProduct = state.products.get(productId);
            if (!originalProduct) return;

            const newProduct = {
                ...originalProduct,
                id: utils.createUniqueId(),
                code: utils.generateProductCode()
            };

            // Add to state
            state.products.set(newProduct.id, newProduct);

            addExistingProduct(newProduct);
            toast.success('Đã nhân bản sản phẩm thành công');
        }

        function addExistingProduct(product) {
            const tbody = document.querySelector('#productsTable tbody');
            const row = document.createElement('tr');
            row.dataset.productId = product.id;
            row.className = 'hover:bg-gray-50 border-b border-gray-200';

            row.innerHTML = `
        ${state.batchMode ? `
            <td class="border-r border-gray-200 p-0">
                <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 rounded m-2"
                       onchange="updateBatchActionVisibility()">
            </td>
        ` : ''}
        <td class="border-r border-gray-200 p-2 text-sm text-gray-500">${product.code}</td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product.name || ''}"
                   placeholder="Nhập tên sản phẩm"
                   onchange="handleInputChange(event, '${product.id}', 'name')">
        </td>
        <td class="border-r border-gray-200 p-1">
            <div class="drop-zone flex items-center gap-2 rounded border border-dashed border-gray-300 hover:border-blue-500 transition-colors">
                <img class="image-preview w-12 h-12 object-cover rounded ${product.image ? '' : 'hidden'}" 
                     src="${product.image || ''}" alt="Preview">
                <label class="cursor-pointer flex-1 text-center py-1">
                    <input type="file" 
                           accept="image/*" 
                           class="hidden" 
                           onchange="handlers.handleImageUpload(event, '${product.id}')">
                    <span class="text-blue-600 hover:text-blue-700 text-sm">Chọn ảnh</span>
                </label>
            </div>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'unit')">
                <option value="">Đơn vị tính</option>
                ${state.units.map(unit => `
                    <option value="${unit}" ${product.unit === unit ? 'selected' : ''}>
                        ${unit}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'category')">
                <option value="">Phân loại</option>
                ${state.categories.map(cat => `
                    <option value="${cat}" ${product.category === cat ? 'selected' : ''}>
                        ${cat}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product.specification || ''}"
                   placeholder="Nhập quy cách"
                   onchange="handleInputChange(event, '${product.id}', 'specification')">
        </td>
        <td class="border-r border-gray-200 p-0">
    <input type="number" 
           class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
           value="${product.purchasePrice || ''}"
           placeholder="Nhập giá nhập"
           onchange="handleInputChange(event, '${product.id}', 'purchasePrice')">
</td>
<td class="border-r border-gray-200 p-0">
    <input type="number" 
           class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
           value="${product.sellingPrice || ''}"
           placeholder="Nhập giá bán"
           onchange="handleInputChange(event, '${product.id}', 'sellingPrice')">
</td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product.note || ''}"
                   placeholder="Nhập ghi chú"
                   onchange="handleInputChange(event, '${product.id}', 'note')">
        </td>
        <td class="p-1 text-center">
            <div class="flex items-center justify-center gap-1">
                <button onclick="deleteProduct('${product.id}')" 
                        class="text-gray-400 hover:text-red-600 transition-colors p-1"
                        title="Xóa sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </button>
                <button onclick="duplicateProduct('${product.id}')" 
                        class="text-gray-400 hover:text-blue-600 transition-colors p-1"
                        title="Nhân bản sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                </button>
            </div>
        </td>
    `;

            tbody.appendChild(row);
            setupDragAndDrop(row);
        }
        // Function to handle file select for Excel import
        function handleFileSelect(input) {
            const file = input.files[0];
            if (file) {
                const fileName = file.name;
                const fileExt = fileName.split('.').pop().toLowerCase();

                if (!['xlsx', 'xls', 'csv'].includes(fileExt)) {
                    toast.error('Vui lòng chọn file Excel (.xlsx, .xls) hoặc CSV');
                    input.value = '';
                    return;
                }

                const fileLabel = input.parentElement.querySelector('span');
                fileLabel.textContent = fileName;
            }
        }

        // Function to read Excel file
        function readExcelFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();

                reader.onload = (e) => {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                        const jsonData = XLSX.utils.sheet_to_json(firstSheet);
                        resolve(jsonData);
                    } catch (error) {
                        reject(error);
                    }
                };

                reader.onerror = (error) => reject(error);
                reader.readAsArrayBuffer(file);
            });
        }

        // Delete product function
        function deleteProduct(productId) {
            if (!confirm('Bạn có chắc chắn muốn xóa sản phẩm này?')) return;

            const row = document.querySelector(`tr[data-product-id="${productId}"]`);
            if (row) {
                row.remove();
                state.products.delete(productId);
                toast.success('Đã xóa sản phẩm');

                // Update batch actions visibility if in batch mode
                if (state.batchMode) {
                    updateBatchActionVisibility();
                }
            }
        }
        // Batch Operations
        function toggleBatchMode() {
            state.batchMode = !state.batchMode;
            const table = document.getElementById('productsTable');
            const checkboxColumns = table.querySelectorAll('.checkbox-column');

            checkboxColumns.forEach(col => {
                col.classList.toggle('hidden', !state.batchMode);
            });

            document.getElementById('toggleBatchMode').classList.toggle('bg-blue-100', state.batchMode);
            updateBatchActionVisibility();
        }

        function toggleAllProducts(checkbox) {
            const table = document.getElementById('productsTable');
            table.querySelectorAll('tbody tr input[type="checkbox"]')
                .forEach(cb => cb.checked = checkbox.checked);
            updateBatchActionVisibility();
        }

        function updateBatchActionVisibility() {
            const batchActions = document.getElementById('batchActions');
            const checkedBoxes = document.querySelectorAll('tbody tr input[type="checkbox"]:checked');
            const selectedCount = document.getElementById('selectedCount');

            selectedCount.textContent = `Đã chọn: ${checkedBoxes.length}`;
            batchActions.classList.toggle('hidden', checkedBoxes.length === 0);
        }

        function getSelectedProducts() {
            const selectedRows = document.querySelectorAll('tbody tr input[type="checkbox"]:checked');
            return Array.from(selectedRows).map(checkbox => dom.getProductId(dom.getProductRow(checkbox)));
        }

        function deleteBatchProducts() {
            const selectedIds = getSelectedProducts();
            if (!selectedIds.length) return;

            if (confirm(`Bạn có chắc chắn muốn xóa ${selectedIds.length} sản phẩm đã chọn?`)) {
                selectedIds.forEach(id => {
                    const row = document.querySelector(`tr[data-product-id="${id}"]`);
                    if (row) {
                        row.remove();
                        state.products.delete(id);
                    }
                });
                toast.success(`Đã xóa ${selectedIds.length} sản phẩm`);
                updateBatchActionVisibility();
            }
        }

        function copyBatchProducts() {
            const selectedIds = getSelectedProducts();
            if (!selectedIds.length) return;

            selectedIds.forEach(id => {
                const originalProduct = state.products.get(id);
                if (originalProduct) {
                    const newProduct = { ...originalProduct };
                    newProduct.id = utils.createUniqueId();
                    newProduct.code = utils.generateProductCode();
                    state.products.set(newProduct.id, newProduct);
                    addExistingProduct(newProduct);
                }
            });

            toast.success(`Đã nhân bản ${selectedIds.length} sản phẩm`);
        }

        // Utility Functions
        const utils = {
            generateProductCode() {
                state.lastProductId++;
                return `SP${String(state.lastProductId).padStart(5, '0')}`;
            },

            createUniqueId() {
                return Date.now().toString(36) + Math.random().toString(36).substr(2);
            },

            validateProduct(product) {
                return product.name?.trim() && product.unit?.trim();
            }
        };


        // Event Listeners
    </script>

</body>

</html>