const addIngredientBtn = document.getElementById('add-ingredient-btn');
const overlay = document.getElementById('overlay');
const ingModal = document.getElementById('ingredient-modal');

addIngredientBtn.addEventListener('click', () => {
    ingModal.classList.remove('hidden');
    overlay.classList.remove('hidden');
});


document.addEventListener('click', (e) => {
    if (!ingModal.contains(e.target) && !addIngredientBtn.contains(e.target)) {
        ingModal.classList.add('hidden');
        overlay.classList.add('hidden');
    }
});

const ingredientSubmitBtn = document.getElementById('new-ingredient-submit');
const ingredientName = document.getElementById('ing-name-input');
const ingredientUnit = document.getElementById('ing-unit-input');

ingredientSubmitBtn.addEventListener('click', async (e) => {

    const name = ingredientName.value.trim();
    const unit = ingredientUnit.value.trim();

    if (!name || !unit) {
        showToastify('Please fill in all fields.', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'create_ingredient');
    formData.append('name', name);
    formData.append('unit', unit);

    const response = await fetch('/ajax', {
        method: 'POST',
        body: formData
    });

    const json = await response.json();

    if (!response.ok) {
        const message = json.error;
        showToastify(message, 'error');
        return;
    }

    showToastify(json.success, 'success');
    ingredientName.value = '';
    ingredientUnit.value = '';
    ingModal.classList.add('hidden');
    overlay.classList.add('hidden');
});


const searchIngredientWrapper = document.getElementById('search-ingredient');
const searchIngInput = searchIngredientWrapper.querySelector('input');
const searchIngDropdown = searchIngredientWrapper.querySelector('.custom-select-dropdown');

const tableIngRows = document.querySelector('.ing-table-rows');
const ingredientsAdded = new Map();

searchIngInput.addEventListener('input', function () {
    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(async () => {
        let searchValue = this.value.trim();


        if (searchValue.length < 3) {
            searchIngInput.innerHTML = '';
            searchIngDropdown.hidden = true;
            return;
        }

        const formData = new FormData();
        formData.append('action', 'search_ingredient');
        formData.append('query', searchValue);

        const response = await fetch('/ajax', {
            method: 'POST',
            body: formData
        });

        const json = await response.json();

        if (!response.ok) {
            const message = json.error || 'Something went wrong.';
            showToastify(message, 'error');
            return;
        }

        const results = json.result;

        searchIngDropdown.innerHTML = '';

        if (results.length > 0) {
            results.forEach(ingredient => {
                const ingredientName = `${ingredient.field_name} (${ingredient.field_unit_name})`;

                const option = document.createElement('div');
                option.className = "dropdown-item hover-anim";
                option.textContent = ingredientName;

                option.addEventListener('click', (e) => {
                    const row = document.createElement('tr');

                    if(ingredientsAdded.get(ingredient.id) != undefined) {
                        showToastify("This field already exists.", "error");
                        return;
                    }

                    row.innerHTML += `
                        <td>${ingredientName}</td>
                        <td>
                            <input class="ing-id" type="number" name="ing-id[]" hidden />
                            <div class="input ing-name"><input type="number" name="ing-count[]" value="1" /></div>
                            <i class="fa-solid fa-trash"></i>
                        </td>
                    `;
                    row.querySelector(".ing-id").value = ingredient.id;
                    

                    const rowDeleteBtn = row.querySelector('i');
                    rowDeleteBtn.addEventListener('click', (e) => {
                        ingredientsAdded.delete(ingredient.id);
                        row.remove();
                    });

                    ingredientsAdded.set(ingredient.id, ingredientName);
                    tableIngRows.append(row);
                    searchIngInput.value = '';
                    searchIngDropdown.hidden = true;
                });

                searchIngDropdown.append(option);
            });
            searchIngDropdown.hidden = false;
        } else {
            searchIngDropdown.innerHTML = `<div class="search-result-item">No recipes found</div>`;
            searchIngDropdown.hidden = false;
        }
    }, 300);
});