from django.shortcuts import render, redirect
from .models import Article, TodoItem
from .forms import TodoItemForm
import time

def index(request):
    if request.method == 'POST':
        form = TodoItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = TodoItemForm()
    
    todo_list = TodoItem.objects.all().order_by('-created_at')
    articles = Article.objects.all()
    
    context = {
        'articles': articles,
        'todo_list': todo_list,
        'form': form,
        'timestamp': int(time.time()),
    }
    return render(request, "core/index.html", context)

def kanban_board(request):
    tasks = TodoItem.objects.all().order_by('created_at')
    tasks_by_status = {
        status_value: list(filter(lambda t: t.status == status_value, tasks))
        for status_value, status_display in TodoItem.STATUS_CHOICES
    }

    context = {
        'tasks_by_status': tasks_by_status,
        'status_choices': TodoItem.STATUS_CHOICES,
        'timestamp': int(time.time()),
    }
    return render(request, "core/kanban.html", context)

def article_detail(request, article_id):
    article = Article.objects.get(pk=article_id)
    return render(request, "core/article_detail.html", {"article": article})