{% extends "base.html" %}
{% block content %}
<div class="row">
    <div class="col-md-12">
        <button type="button" class="btn btn-primary btn-lg mb-4" data-bs-toggle="modal" data-bs-target="#addFoodModal" data-testid="add-new-food">
            <i class="bi bi-plus-circle"></i> Add New Food
        </button>
        
        <button type="button" class="btn btn-secondary btn-lg mb-4" data-bs-toggle="modal" data-bs-target="#addFromOpenFoodFactsModal" data-testid="add-from-open-food-facts">
            <i class="bi bi-search"></i> Add from Open Food Facts
        </button>
        
        <h3>Foods Database</h3>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Select</th>
                        <th>Name</th>
                        <th>Brand</th>
                        <th>Serving</th>
                        <th>Cal</th>
                        <th>Protein</th>
                        <th>Carbs</th>
                        <th>Fat</th>
                        <th>Fiber</th>
                        <th>Sodium</th>
                        <th>Calcium</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for food in foods %}
                    {% set food_name_slug = food.name|lower|replace(' ', '-')|replace(',', '')|replace('.', '') %}
                    <tr data-testid="food-row-{{ food_name_slug }}-{{ loop.index }}">
                        <td><input type="checkbox" name="selected_foods" value="{{ food.id }}" data-testid="select-food-{{ food_name_slug }}-{{ loop.index }}"></td>
                        <td data-testid="food-name-{{ food_name_slug }}-{{ loop.index }}">{{ food.name }}</td>
                        <td data-testid="food-brand-{{ food_name_slug }}-{{ loop.index }}">{{ food.brand or '' }}</td>
                        <td data-testid="food-serving-{{ food_name_slug }}-{{ loop.index }}">{{ food.serving_size }} {{ food.serving_unit }}</td>
                        <td data-testid="food-calories-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.calories) }}</td>
                        <td data-testid="food-protein-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.protein) }}g</td>
                        <td data-testid="food-carbs-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.carbs) }}g</td>
                        <td data-testid="food-fat-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.fat) }}g</td>
                        <td data-testid="food-fiber-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.fiber) }}g</td>
                        <td data-testid="food-sodium-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.sodium) }}mg</td>
                        <td data-testid="food-calcium-{{ food_name_slug }}-{{ loop.index }}">{{ "%.2f"|format(food.calcium) }}mg</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-outline-primary"
                                    onclick="editFood({{ food.id }})" data-testid="edit-food-{{ food_name_slug }}-{{ loop.index }}">
                                <i class="bi bi-pencil"></i> Edit
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <button class="btn btn-danger mt-3" onclick="deleteSelectedFoods()" data-testid="delete-selected-foods">
            <i class="bi bi-trash"></i> Delete Selected Foods
        </button>
    </div>
</div>

{% include 'modals/add_from_open_food_facts.html' %}

<!-- Add Food Modal -->
<div class="modal fade" id="addFoodModal" tabindex="-1" aria-labelledby="addFoodModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addFoodModalLabel">Add New Food</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addFoodForm" action="/foods/add" method="post">
                    <div class="row">
                        <div class="col-8 mb-3">
                            <label class="form-label">Name</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="col-4 mb-3">
                            <label class="form-label">Brand</label>
                            <input type="text" class="form-control" name="brand" placeholder="Optional">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Serving Size</label>
                            <input type="text" class="form-control" name="serving_size" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Unit</label>
                            <input type="text" class="form-control" name="serving_unit" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Calories</label>
                            <input type="number" step="0.1" class="form-control" name="calories" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Protein (g)</label>
                            <input type="number" step="0.1" class="form-control" name="protein" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Carbs (g)</label>
                            <input type="number" step="0.1" class="form-control" name="carbs" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Fat (g)</label>
                            <input type="number" step="0.1" class="form-control" name="fat" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Fiber (g)</label>
                            <input type="number" step="0.1" class="form-control" name="fiber" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Sugar (g)</label>
                            <input type="number" step="0.1" class="form-control" name="sugar" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Sodium (mg)</label>
                            <input type="number" step="0.1" class="form-control" name="sodium" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Calcium (mg)</label>
                            <input type="number" step="0.1" class="form-control" name="calcium" value="0">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitFoodForm('add')">Add Food</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Food Modal -->
<div class="modal fade" id="editFoodModal" tabindex="-1" aria-labelledby="editFoodModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editFoodModalLabel">Edit Food</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editFoodForm" action="/foods/edit" method="post">
                    <input type="hidden" name="food_id" id="edit_food_id">
                    <div class="row">
                        <div class="col-8 mb-3">
                            <label class="form-label">Name</label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="col-4 mb-3">
                            <label class="form-label">Brand</label>
                            <input type="text" class="form-control" name="brand" id="edit_brand" placeholder="Optional">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Serving Size</label>
                            <input type="text" class="form-control" name="serving_size" id="edit_serving_size" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Unit</label>
                            <input type="text" class="form-control" name="serving_unit" id="edit_serving_unit" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Calories</label>
                            <input type="number" step="0.1" class="form-control" name="calories" id="edit_calories" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Protein (g)</label>
                            <input type="number" step="0.1" class="form-control" name="protein" id="edit_protein" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Carbs (g)</label>
                            <input type="number" step="0.1" class="form-control" name="carbs" id="edit_carbs" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Fat (g)</label>
                            <input type="number" step="0.1" class="form-control" name="fat" id="edit_fat" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Fiber (g)</label>
                            <input type="number" step="0.1" class="form-control" name="fiber" id="edit_fiber">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Sugar (g)</label>
                            <input type="number" step="0.1" class="form-control" name="sugar" id="edit_sugar">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Sodium (mg)</label>
                            <input type="number" step="0.1" class="form-control" name="sodium" id="edit_sodium">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Calcium (mg)</label>
                            <input type="number" step="0.1" class="form-control" name="calcium" id="edit_calcium">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitFoodForm('edit')">Update Food</button>
            </div>
        </div>
    </div>
</div>

<script>
// Edit food function
function editFood(foodId) {
    // This function will be implemented after page load using the food data
    // For now, we'll use a placeholder that will be replaced by the actual implementation
    console.log("Edit food called for ID:", foodId);
}

// Submit food form (add or edit)
async function submitFoodForm(action) {
    const form = document.getElementById(action + 'FoodForm');
    const formData = new FormData(form);
    
    try {
        const response = await fetch(form.action, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            // Close modal and reload page
            bootstrap.Modal.getInstance(document.getElementById(action + 'FoodModal')).hide();
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error submitting form: ' + error.message);
    }
}

// Delete selected foods
async function deleteSelectedFoods() {
    const selected = Array.from(document.querySelectorAll('input[name="selected_foods"]:checked'))
        .map(checkbox => checkbox.value);

    if (selected.length === 0) {
        alert('Please select foods to delete');
        return;
    }

    if (confirm(`Delete ${selected.length} selected foods?`)) {
        try {
            const response = await fetch('/foods/delete', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({food_ids: selected})
            });

            const result = await response.json();

            if (response.ok) {
                window.location.reload();
            } else {
                alert(`Delete failed: ${result.message || response.status}`);
            }
        } catch (error) {
            alert('Delete failed: ' + error.message);
        }
    }
}

// Initialize editFood function after page load
document.addEventListener('DOMContentLoaded', function() {
    const foodsData = {
        {% for food in foods %}
        {{ food.id }}: {
            name: '{{ food.name | replace("'", "\\'") }}',
            brand: '{{ food.brand | replace("'", "\\'") }}',
            serving_size: '{{ food.serving_size | replace("'", "\\'") }}',
            serving_unit: '{{ food.serving_unit | replace("'", "\\'") }}',
            calories: {{ food.calories }},
            protein: {{ food.protein }},
            carbs: {{ food.carbs }},
            fat: {{ food.fat }},
            fiber: {{ food.fiber }},
            sugar: {{ food.sugar }},
            sodium: {{ food.sodium }},
            calcium: {{ food.calcium }}
        },
        {% endfor %}
    };

    // Implement the actual editFood function
    window.editFood = function(foodId) {
        const food = foodsData[foodId];
        if (!food) return;

        document.getElementById('edit_food_id').value = foodId;
        document.getElementById('edit_name').value = food.name;
        document.getElementById('edit_brand').value = food.brand || '';
        document.getElementById('edit_serving_size').value = food.serving_size;
        document.getElementById('edit_serving_unit').value = food.serving_unit;
        document.getElementById('edit_calories').value = food.calories;
        document.getElementById('edit_protein').value = food.protein;
        document.getElementById('edit_carbs').value = food.carbs;
        document.getElementById('edit_fat').value = food.fat;
        document.getElementById('edit_fiber').value = food.fiber;
        document.getElementById('edit_sugar').value = food.sugar;
        document.getElementById('edit_sodium').value = food.sodium;
        document.getElementById('edit_calcium').value = food.calcium;

        new bootstrap.Modal(document.getElementById('editFoodModal')).show();
    };
});
</script>

<script>
// Open Food Facts Modal Logic
async function searchOpenFoodFacts() {
    const query = document.querySelector('#addFromOpenFoodFactsModal input[name="openfoodfacts_query"]').value;
    const resultsContainer = document.getElementById('openFoodFactsResults');
    resultsContainer.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div>';

    try {
        const response = await fetch(`/foods/search_openfoodfacts?query=${query}`);
        const data = await response.json();
        
        resultsContainer.innerHTML = ''; // Clear spinner here, before populating or showing "no results"

        if (data.status === 'success' && data.results.length > 0) {
            data.results.forEach(food => {
                const item = document.createElement('a');
                item.href = '#';
                item.className = 'list-group-item list-group-item-action';
                item.textContent = `${food.name} - ${food.brand}`;
                item.onclick = (e) => {
                    e.preventDefault();
                    selectOpenFoodFactsProduct(food);
                };
                resultsContainer.appendChild(item);
            });
        } else {
            resultsContainer.innerHTML = `<div class="list-group-item">No results found.</div>`;
        }
    } catch (error) {
        resultsContainer.innerHTML = `<div class="list-group-item">Error: ${error.message}</div>`;
    }
}

function selectOpenFoodFactsProduct(food) {
    const form = document.getElementById('addOpenFoodFactsForm');
    form.querySelector('input[name="name"]').value = food.name;
    form.querySelector('input[name="brand"]').value = food.brand;
    form.querySelector('input[name="serving_size"]').value = food.serving_size;
    form.querySelector('input[name="serving_unit"]').value = food.serving_unit;
    form.querySelector('input[name="calories"]').value = food.calories;
    form.querySelector('input[name="protein"]').value = food.protein;
    form.querySelector('input[name="carbs"]').value = food.carbs;
    form.querySelector('input[name="fat"]').value = food.fat;
    form.querySelector('input[name="fiber"]').value = food.fiber;
    form.querySelector('input[name="sugar"]').value = food.sugar;
    form.querySelector('input[name="sodium"]').value = food.sodium;
    form.querySelector('input[name="calcium"]').value = food.calcium;
    form.querySelector('input[name="openfoodfacts_id"]').value = food.openfoodfacts_id;
}

async function submitOpenFoodFactsForm() {
    const form = document.getElementById('addOpenFoodFactsForm');
    const formData = new FormData(form);

    try {
        const response = await fetch(form.action, {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('addFromOpenFoodFactsModal')).hide();
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error submitting form: ' + error.message);
    }
}
</script>
{% endblock %}