let allSkus = [];

document.addEventListener('DOMContentLoaded', async () => {
    await loadProductsForFilter(); // Load products for filter dropdown
    await loadProductsForSelection(); // Load products for selection dropdown
    await loadInventory();
});

async function loadInventory() {
    try {
        allSkus = await app.apiGet('/skus');
        displayInventory(allSkus);
    } catch (error) {
        console.error('Error loading inventory:', error);
        document.getElementById('inventoryTableBody').innerHTML =
            '<tr><td colspan="9" class="loading">Failed to load inventory</td></tr>';
    }
}

function displayInventory(skus) {
    const tbody = document.getElementById('inventoryTableBody');

    if (skus.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" class="loading">No SKUs found</td></tr>';
        return;
    }

    tbody.innerHTML = skus.map(sku => {
        const stockValue = sku.current_stock * sku.price;
        const stockClass = sku.current_stock < 5 ? 'text-danger' : sku.current_stock < 10 ? 'text-warning' : '';

        return `
            <tr class="fade-in">
                <td><strong>${sku.sku_code}</strong></td>
                <td>${sku.product_name}</td>
                <td>${sku.flavour}</td>
                <td>${sku.weight}</td>
                <td><span class="badge badge-primary">${sku.tag || '-'}</span></td>
                <td class="${stockClass}">
                    ${sku.current_stock}
                    ${sku.current_stock < 5 ? '<span class="badge badge-low-stock">Low</span>' : ''}
                </td>
                <td>${app.formatCurrency(sku.price)}</td>
                <td><strong>${app.formatCurrency(stockValue)}</strong></td>
                <td>
                    <button class="btn btn-secondary" onclick="openEditStockModal(${sku.id})" style="padding: 0.5rem 1rem; font-size: 0.75rem;">
                        Edit
                    </button>
                    <button class="btn btn-danger" onclick="deleteSku(${sku.id})" style="padding: 0.5rem 1rem; font-size: 0.75rem; margin-left: 0.5rem;">
                        Delete
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

// Load products to populate the filter dropdown
async function loadProductsForFilter() {
    try {
        const products = await app.apiGet('/products');

        // Update the product filter dropdown
        const productFilter = document.getElementById('productFilter');
        productFilter.innerHTML = '<option value="">All Products</option>';

        products.forEach(product => {
            const option = document.createElement('option');
            option.value = product.name;
            option.textContent = product.name;
            productFilter.appendChild(option);
        });

        // Also update the product selection dropdown in the add SKU modal
        await loadProductsForSelection();
    } catch (error) {
        console.error('Error loading products for filter:', error);
    }
}

// Load products to populate the selection dropdown in the add SKU modal
async function loadProductsForSelection() {
    try {
        const products = await app.apiGet('/products');

        // Update the product selection dropdown in the add SKU modal
        const productSelect = document.getElementById('newProductSelect');
        // Preserve the first option
        productSelect.innerHTML = '<option value="">Select Existing or Create New</option>';

        products.forEach(product => {
            const option = document.createElement('option');
            option.value = product.id;
            option.textContent = product.name;
            productSelect.appendChild(option);
        });
    } catch (error) {
        console.error('Error loading products for selection:', error);
    }
}

function filterInventory() {
    const productFilter = document.getElementById('productFilter').value.toLowerCase();
    const searchTerm = document.getElementById('searchSku').value.toLowerCase();

    const filtered = allSkus.filter(sku => {
        const matchesProduct = !productFilter || sku.product_name.toLowerCase() === productFilter;
        const matchesSearch = !searchTerm ||
            sku.sku_code.toLowerCase().includes(searchTerm) ||
            sku.flavour.toLowerCase().includes(searchTerm);

        return matchesProduct && matchesSearch;
    });

    displayInventory(filtered);
}

function openEditStockModal(skuId) {
    const sku = allSkus.find(s => s.id === skuId);
    if (!sku) return;

    document.getElementById('editSkuId').value = sku.id;
    document.getElementById('editSkuCode').value = sku.sku_code;
    document.getElementById('editProductDetails').value = `${sku.product_name} - ${sku.flavour} (${sku.weight})`;
    document.getElementById('editCurrentStock').value = sku.current_stock;
    document.getElementById('editPrice').value = sku.price;
    document.getElementById('editTag').value = sku.tag || '';

    document.getElementById('editStockModal').classList.add('active');
}

function closeEditStockModal() {
    document.getElementById('editStockModal').classList.remove('active');
    document.getElementById('editStockForm').reset();
}

async function updateStock(event) {
    event.preventDefault();

    const skuId = document.getElementById('editSkuId').value;
    const currentStock = parseInt(document.getElementById('editCurrentStock').value);
    const price = parseFloat(document.getElementById('editPrice').value);
    const tag = document.getElementById('editTag').value;

    try {
        await app.apiPut(`/skus/${skuId}`, { current_stock: currentStock, price, tag });
        app.showNotification('Stock updated successfully', 'success');
        closeEditStockModal();
        await loadInventory();
    } catch (error) {
        console.error('Error updating stock:', error);
        app.showNotification('Failed to update stock', 'error');
    }
}

async function deleteSku(id) {
    if (confirm('Are you sure you want to delete this product? This action cannot be undone.')) {
        try {
            await app.apiDelete(`/skus/${id}`);
            app.showNotification('Product deleted successfully', 'success');
            await loadInventory();
        } catch (error) {
            console.error('Error deleting SKU:', error);
            app.showNotification('Failed to delete product', 'error');
        }
    }
}

function openAddSkuModal() {
    document.getElementById('addSkuModal').classList.add('active');
}

function closeAddSkuModal() {
    document.getElementById('addSkuModal').classList.remove('active');
    document.getElementById('addSkuForm').reset();
    // Reset the category input visibility
    document.getElementById('newProductCategory').style.display = 'none';
    document.getElementById('newProductSelect').value = '';
}

function toggleCategoryInput() {
    const selectElement = document.getElementById('newProductSelect');
    const inputElement = document.getElementById('newProductCategory');
    const hiddenProductId = document.getElementById('newProductId');

    if (selectElement.value === '') {
        // Show input field for new category
        inputElement.style.display = 'block';
    } else {
        // Hide input field and use selected product
        inputElement.style.display = 'none';
        hiddenProductId.value = selectElement.value;
    }
}

async function addNewSku(event) {
    event.preventDefault();

    const selectElement = document.getElementById('newProductSelect');
    const inputElement = document.getElementById('newProductCategory');
    let productId = null;
    let categoryName = '';

    // Check if user wants to create a new category (when input field is visible and has value)
    if (inputElement.style.display === 'block' && inputElement.value.trim() !== '') {
        categoryName = inputElement.value.trim();

        // Validate category name
        if (!categoryName) {
            app.showNotification('Please enter a product category name', 'error');
            return;
        }

        if (categoryName.length > 50) {
            app.showNotification('Category name must be 50 characters or less', 'error');
            return;
        }
    } else if (selectElement.value === '') {
        app.showNotification('Please select a category or enter a new one', 'error');
        return;
    }

    try {
        // If creating a new category
        if (categoryName) {
            // First create the new product category
            const newProductResponse = await app.apiPost('/products', {
                name: categoryName,
                description: ''
            });

            productId = newProductResponse.id;
        } else {
            // Use existing product
            productId = parseInt(selectElement.value);
        }

        // Create the SKU with the product ID
        const skuData = {
            sku_code: document.getElementById('newSkuCode').value,
            product_id: parseInt(productId),
            flavour: document.getElementById('newFlavour').value,
            weight: document.getElementById('newWeight').value,
            current_stock: parseInt(document.getElementById('newStock').value),
            price: parseFloat(document.getElementById('newPrice').value),
            tag: document.getElementById('newTag').value
        };

        await app.apiPost('/skus', skuData);
        app.showNotification('New SKU added successfully', 'success');

        // If a new product was created, refresh the product dropdowns
        if (categoryName) {
            await loadProductsForFilter();
            await loadProductsForSelection();
        }

        closeAddSkuModal();
        await loadInventory();
    } catch (error) {
        console.error('Error adding SKU:', error);
        if (error.message.includes('UNIQUE constraint failed')) {
            app.showNotification('SKU code already exists. Please use a unique SKU code.', 'error');
        } else if (error.message.includes('Product name already exists')) {
            app.showNotification('Product category already exists. Please select it from the dropdown.', 'error');
        } else {
            app.showNotification('Failed to add SKU. Please check your inputs.', 'error');
        }
    }
}
