#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
#include "todo.h"

#define MAX_TASKS 100

Task tasks[MAX_TASKS]; 
int task_count = 0;
int selected_task = 0;

// Function to clear input prompt after getting the input
void get_input_and_clear(char *buffer, int size, const char *prompt) {
    mvprintw(LINES - 2, 0, "%s", prompt);
    clrtoeol();  // Clears the prompt area before input to avoid overlay
    echo();
    getnstr(buffer, size - 1);  // Get user input
    noecho();
    buffer[size - 1] = '\0';  // Null-terminate the string
    clear();  // Clear the entire screen after each input
    refresh();
}

void add_task_interactive() {
    char title[MAX_TITLE_LEN];
    char category[MAX_CATEGORY_LEN];
    char due_date[MAX_DATE_LEN];
    int priority;

    // Get valid inputs and clear screen after each prompt
    get_input_and_clear(title, MAX_TITLE_LEN, "Enter task title: ");
    get_input_and_clear(category, MAX_CATEGORY_LEN, "Enter category: ");
    get_input_and_clear(due_date, MAX_DATE_LEN, "Enter due date (YYYY-MM-DD): ");

    // Enable echoing for priority input so the user can see what they type
    mvprintw(LINES - 2, 0, "Enter priority (1-5): ");
    clrtoeol();
    echo();  // Enable echoing so input is visible
    scanw("%d", &priority);
    noecho();  // Disable echoing again after input is done

    // Add the task using the gathered inputs
    add_task(tasks, &task_count, title, category, due_date, "none", priority);

    // Confirmation and refresh
    mvprintw(LINES - 2, 0, "Task added successfully! Press any key...");
    clrtoeol();
    refresh();
    getch();
}

void delete_task_interactive() {
    remove_task(tasks, &task_count, tasks[selected_task].id);
    if (selected_task > 0) selected_task--;
}

int main() {
    init_ncurses();
    load_tasks(tasks, &task_count);

    int ch;
    while ((ch = getch()) != 'q') {
        switch (ch) {
            case 'j':
                if (selected_task < task_count - 1) selected_task++;
                break;
            case 'k':
                if (selected_task > 0) selected_task--;
                break;
            case 'a':
                add_task_interactive();
                break;
            case 'd':
                delete_task_interactive();
                break;
            case 'c':
                toggle_task_completion(&tasks[selected_task]);
                break;
        }

        display_tasks(tasks, task_count, selected_task);
    }

    save_tasks(tasks, task_count);
    cleanup_ncurses();
    return 0;
}
