<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ .title }}</title>
    {{template "head" .}}
</head>
<body>
{{template "navbar" .}}

<div class="container">
    <div class="mt-5 d-flex justify-content-between align-items-center">
        <div class="fs-3 text-center">{{ .title }}</div>
        <div class="col-6">
            <input type="email" class="form-control" id="search" placeholder="search for task">
        </div>
    </div>
    <hr>
    <div id="tasks"></div>
    <hr>
    <form class="row g-3 needs-validation" novalidate>
        <div class="col-1"></div>
        <div class="col-8">
            <div class="input-group has-validation">
                <input type="text" class="form-control" id="description" required>
                <div class="invalid-feedback">
                    Please provide a description.
                </div>
            </div>
        </div>
        <div class="col-3">
            <button class="btn btn-primary" id="button" type="submit"><i class="bi bi-plus-lg"></i></button>
        </div>
    </form>
</div>

{{template "scripts" .}}
{{template "formScripts" .}}
<script>
    userLoggedIn().then((loggedIn) => !loggedIn ? redirect("/view/login") : getAllTasks());
    const tasksEl = document.getElementById("tasks");
    const descriptionInput = document.getElementById("description");
    let tasks = [];
    let timer;

    document.getElementById("search").addEventListener('keyup', e => {
        const enteredText = e.currentTarget.value;
        clearTimeout(timer);
        if (e.key === "Enter ") {
            getAllTasks(enteredText);
        } else {
            timer = setTimeout(() => {
                getAllTasks(enteredText);
            }, 1000);
        }
    });

    function submitForm(formData) {
        axios.post("/tasks", formData, axiosConfig)
            .then((response) => {
                addTaskToTasks(response.data.task, tasks.length + 1);
                form.classList.remove('was-validated');
                descriptionInput.value = "";
            })
            .catch((err) => {
                showErrorToast(err.response.data.message);
            });
    }

    function deleteTask(id) {
        axios.delete("/tasks", {params: {id: id}, headers: {username: username}})
            .then(() => {
                getAllTasks();
            })
            .catch((err) => {
                showErrorToast(err.response.data.message);
            });
    }

    function updateTask(id, done) {
        axios.put("/tasks", null, {params: {id: id, done: done}, headers: {username: username}})
            .catch((err) => {
                showErrorToast(err.response.data.message);
            });
    }

    function addTaskToTasks(task, number) {
        tasks.push(task);
        const newTask = document.createElement('div');
        newTask.classList.add('row', 'g-0', 'align-items-center', 'mb-1');
        newTask.id = task.ID;
        newTask.innerHTML = `
                        <div class="col-1 text-center">${number}</div>
                        <div class="col-8">${task.Description}</div>
                        <div class="col-2 form-check form-switch d-flex justify-content-center">
                          <input onchange="updateTask(${task.ID},this.checked)" class="text-center form-check-input" type="checkbox" ${task.Done && "checked"} role="switch" id="flexSwitchCheckDefault">
                        </div>
                        <button onclick="deleteTask(${task.ID})" class="col-1 btn btn-danger"><i class="bi bi-trash"></i></button>
                    `;
        tasksEl.appendChild(newTask);
    }

    function addTaskHeader() {
        const taskHeader = document.createElement("div");
        taskHeader.classList.add('row', 'g-0', 'align-items-center', 'mb-1');
        taskHeader.innerHTML = `
                <div class="fw-bold col-1 text-center">ID</div>
                <div class="fw-bold col-8">Description</div>
                <div class="fw-bold col-2 text-center">Done</div>
                <div class="fw-bold col-1 text-center">Delete</div>
                <hr class="mt-3 mb-2">
            `;
        tasksEl.appendChild(taskHeader);
    }

    function getAllTasks(filter) {
        tasksEl.innerHTML = "";
        addTaskHeader();
        axios.get("/tasks", {params: {filter: filter}, headers: {username: username}}).then((response) => {
            tasks = response.data.tasks;
            tasks.forEach((task, index) => {
                addTaskToTasks(task, index + 1);
            });
        });
    }
</script>
</body>
</html>
