document.addEventListener('DOMContentLoaded', () => {
    const recipeNameInput = document.getElementById('recipeNameInput');
    const ingredientNameInput = document.getElementById('ingredientNameInput');
    const quantityInput = document.getElementById('quantityInput');
    const unitSelect = document.getElementById('unitSelect');
    const recipeStatus = document.getElementById('recipeStatus');
    const ingredientTableBody = document.querySelector('#displayListTable tbody');
    const addIngredientButton = document.getElementById('addIngredient');
    const exportPDFButton = document.getElementById('exportPDF');
    const currentRecipeStatus = document.getElementById('currentRecipeStatus');

    // Load saved recipe from Local Storage when the page loads
    loadRecipeFromLocalStorage();

    // Add ingredient to the table and save to Local Storage
    addIngredientButton.addEventListener('click', () => {
        const ingredientName = ingredientNameInput.value.trim();
        const quantity = parseFloat(quantityInput.value);
        const unit = unitSelect.value;

        if (!ingredientName || isNaN(quantity) || quantity <= 0) {
            alert('Please enter valid ingredient details.');
            return;
        }

        addIngredientToTable(ingredientName, quantity, unit);
        saveRecipeToLocalStorage();
        clearIngredientInputs();
    });

    // Update recipe status and save to Local Storage
    recipeStatus.addEventListener('change', () => {
        currentRecipeStatus.textContent = recipeStatus.value;
        saveRecipeToLocalStorage();
    });

    // Export recipe to PDF and save to Local Storage
    exportPDFButton.addEventListener('click', () => {
        exportRecipeToPDF();
        saveRecipeToLocalStorage();
    });

    // Set the current date in the Date input field
    window.onload = function () {
        const dateInput = document.getElementById('dateInput');
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        dateInput.value = formattedDate;
    };

    // Add ingredient row to the table
    function addIngredientToTable(name, quantity, unit) {
        const totalQuantity = calculateTotalQuantity() + quantity;

        const row = document.createElement('tr');
        const rowIndex = ingredientTableBody.rows.length + 1;

        const percentage = ((quantity / totalQuantity) * 100).toFixed(2);

        row.innerHTML = `
            <td>${rowIndex}</td>
            <td>${name}</td>
            <td>${quantity}</td>
            <td>${unit}</td>
            <td>${percentage}%</td>
            <td>
                <button class="btn btn-warning btn-sm editBtn"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm deleteBtn"><i class="fas fa-trash-alt"></i></button>
            </td>
        `;

        // Add event listeners for edit and delete buttons
        const editBtn = row.querySelector('.editBtn');
        const deleteBtn = row.querySelector('.deleteBtn');

        editBtn.addEventListener('click', () => editIngredient(row));
        deleteBtn.addEventListener('click', () => deleteIngredient(row));

        ingredientTableBody.appendChild(row);
        updatePercentages();
    }

    // Calculate the total quantity of all ingredients
    function calculateTotalQuantity() {
        let total = 0;
        ingredientTableBody.querySelectorAll('tr').forEach(row => {
            const quantity = parseFloat(row.cells[2].textContent);
            total += quantity;
        });
        return total;
    }

    // Update the percentage column for all ingredients
    function updatePercentages() {
        const totalQuantity = calculateTotalQuantity();
        ingredientTableBody.querySelectorAll('tr').forEach(row => {
            const quantity = parseFloat(row.cells[2].textContent);
            const percentage = ((quantity / totalQuantity) * 100).toFixed(2);
            row.cells[4].textContent = `${percentage}%`;
        });
    }

    // Clear input fields after adding an ingredient
    function clearIngredientInputs() {
        ingredientNameInput.value = '';
        quantityInput.value = '';
        unitSelect.value = 'grams';
    }

    // Edit an existing ingredient
    function editIngredient(row) {
        const cells = row.cells;
        ingredientNameInput.value = cells[1].textContent;
        quantityInput.value = parseFloat(cells[2].textContent);
        unitSelect.value = cells[3].textContent;

        row.remove();
        updatePercentages();
        saveRecipeToLocalStorage();
    }

    // Delete an ingredient
    function deleteIngredient(row) {
        row.remove();
        updatePercentages();
        saveRecipeToLocalStorage();
    }

    // Save the current recipe to Local Storage
    function saveRecipeToLocalStorage() {
        const recipeName = recipeNameInput.value.trim();
        const status = recipeStatus.value;
        const ingredients = [];

        ingredientTableBody.querySelectorAll('tr').forEach(row => {
            const cells = row.cells;
            ingredients.push({
                name: cells[1].textContent,
                quantity: parseFloat(cells[2].textContent),
                unit: cells[3].textContent,
                percentage: cells[4].textContent
            });
        });

        const recipe = {
            name: recipeName,
            status: status,
            ingredients: ingredients
        };

        localStorage.setItem('savedRecipe', JSON.stringify(recipe));
    }

    // Load recipe from Local Storage
    function loadRecipeFromLocalStorage() {
        const savedRecipe = JSON.parse(localStorage.getItem('savedRecipe'));
        if (savedRecipe) {
            recipeNameInput.value = savedRecipe.name || '';
            recipeStatus.value = savedRecipe.status || 'Draft';
            currentRecipeStatus.textContent = savedRecipe.status || 'Draft';

            savedRecipe.ingredients.forEach(ingredient => {
                addIngredientToTable(ingredient.name, ingredient.quantity, ingredient.unit);
            });
        }
    }

    // Export recipe to PDF
    function exportRecipeToPDF() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();

        const dateInput = document.getElementById('dateInput');
        const currentDate = dateInput.value || new Date().toLocaleDateString();

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(18);
        doc.text('Recipe Details', 105, 20, { align: 'center' });

        doc.setFontSize(12);
        doc.setFont('helvetica', 'normal');
        doc.text(`Recipe Name: ${recipeNameInput.value}`, 20, 40);
        doc.text(`Recipe Status: ${recipeStatus.value}`, 20, 50);
        doc.text(`Date: ${currentDate}`, 20, 60);

        doc.setDrawColor(0);
        doc.line(20, 65, 190, 65);

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(14);
        doc.text('Ingredients:', 20, 75);

        const tableStartY = 85;
        let y = tableStartY;

        doc.setFontSize(12);
        doc.setFont('helvetica', 'bold');
        doc.text('No.', 20, y);
        doc.text('Ingredient', 40, y);
        doc.text('Quantity', 90, y);
        doc.text('Unit', 130, y);
        doc.text('Percentage', 160, y);

        y += 2;
        doc.line(20, y, 190, y);

        y += 8;
        doc.setFont('helvetica', 'normal');
        let rowCount = 1;

        ingredientTableBody.querySelectorAll('tr').forEach(row => {
            const cells = row.cells;

            doc.text(rowCount.toString(), 20, y);
            doc.text(cells[1].textContent, 40, y);
            doc.text(cells[2].textContent, 90, y);
            doc.text(cells[3].textContent, 130, y);
            doc.text(cells[4].textContent, 160, y);

            y += 8;
            rowCount++;
        });

        doc.setFontSize(10);
        doc.setFont('helvetica', 'italic');
        doc.text('Generated with the Recipe Manager App', 105, 290, { align: 'center' });

        doc.save(`${recipeNameInput.value || 'Recipe'}_${currentDate}.pdf`);
    }
});