from flask import Blueprint, render_template, request, abort
from flask_login import login_required

from app.services.permissions import require
from app.services import task_queries
from config import TASK_CATEGORIES

bp = Blueprint("tasks", __name__, url_prefix="/tasks")
CATEGORY_MAP = {c["key"]: c for c in TASK_CATEGORIES}


@bp.route("/")
@login_required
@require("tasks")
def index():
    counts = task_queries.get_category_counts()
    return render_template("tasks/index.html", categories=TASK_CATEGORIES, counts=counts)


@bp.route("/<key>")
@login_required
@require("tasks")
def result(key):
    category = CATEGORY_MAP.get(key) or abort(404)
    all_rows = task_queries.get_category_customers(key)

    search = request.args.get("q", "").strip().lower()
    city = request.args.get("city") or None
    cities = sorted({c.city for c in all_rows if c.city})

    rows = all_rows
    if city:
        rows = [c for c in rows if c.city == city]
    if search:
        rows = [c for c in rows if search in f"{c.first_name} {c.last_name}".lower()
                or search in (c.mobile_phone or "")]

    return render_template("tasks/result.html", category=category, rows=rows, cities=cities,
                            q=request.args.get("q", ""), selected_city=city)
