import urllib.parse
from typing import Annotated

from fastapi import Request
from fastapi.params import Param
from folkugat_web.api.router import get_router
from folkugat_web.fragments import temes
from folkugat_web.model.search import Order, OrderBy, OrderParams
from folkugat_web.services import auth
from folkugat_web.templates import templates

router = get_router()


@router.get("/temes")
def page(
    request: Request,
    logged_in: auth.LoggedIn,
    query: Annotated[str, Param()] = "",
    properties: Annotated[list[str] | None, Param()] = None,
    order_by: OrderBy | None = None,
    order: Order = Order.DESC,
):
    properties = properties or []
    order_params = OrderParams(order_by=order_by, order=order) if order_by else None
    temes_params = temes.build_temes_params(
        query=query,
        properties=properties,
        order_params=order_params,
    )
    content_url = f"/api/content/temes?{temes_params}"
    if query:
        additional_description = f" - Resultats per a '{query}'"
    else:
        additional_description = ""
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "page_title": "Folkugat - Temes",
            "page_description": f"Buscador de temes{additional_description}",
            "content": content_url,
            "logged_in": logged_in,
            "animate": False,
        }
    )


@router.get("/api/content/temes")
def content(
    request: Request,
    logged_in: auth.LoggedIn,
    query: Annotated[str, Param()] = "",
    properties: Annotated[list[str] | None, Param()] = None,
    order_by: OrderBy | None = None,
    order: Order = Order.DESC,
):
    properties = properties or []
    if not query and not order_by:
        order_by = OrderBy.TIMES_PLAYED
    order_params = OrderParams(order_by=order_by, order=order) if order_by else None
    return temes.temes_pagina(
        request=request,
        logged_in=logged_in,
        query=query,
        properties=properties,
        order_params=order_params,
    )


@router.get("/api/temes/busca")
def busca(
    request: Request,
    logged_in: auth.LoggedIn,
    query: Annotated[str, Param()],
    properties: Annotated[list[str] | None, Param()] = None,
    order_by: OrderBy | None = None,
    order: Order = Order.DESC,
    limit: int = 10,
    offset: int = 0,
):
    order_params = OrderParams(order_by=order_by, order=order) if order_by else None
    return temes.temes_busca(
        request=request,
        query=query,
        properties=properties or [],
        order_params=order_params,
        limit=limit,
        offset=offset,
        logged_in=logged_in,
    )
