"""UI page rendering and form action endpoints."""

from typing import Annotated

from bson import ObjectId
from fastapi import APIRouter, Form
from fastapi.params import Query
from pydantic import BeforeValidator
from starlette.responses import HTMLResponse, RedirectResponse

from app.core.db import DataStatus
from app.core.types import AppView
from mm_base6 import cbv, redirect

router = APIRouter(include_in_schema=False)


def empty_to_none(v: str | None) -> str | None:
    """Convert empty string to None for optional query params."""
    if v == "":
        return None
    return v


@cbv(router)
class PageRouter(AppView):
    """UI page rendering endpoints."""

    @router.get("/")
    async def index(self) -> HTMLResponse:
        """GET: Render home page."""
        return await self.render.html("index.j2")

    @router.get("/data")
    async def data(
        self,
        status: Annotated[DataStatus | None, BeforeValidator(empty_to_none), Query()] = None,
        limit: Annotated[int, Query()] = 100,
    ) -> HTMLResponse:
        """GET: Render data listing page with optional status filter."""
        query = {"status": status} if status else {}
        data = await self.core.db.data.find(query, "-created_at", limit)
        statuses = list(DataStatus)
        return await self.render.html("data.j2", data_list=data, statuses=statuses, form={"status": status, "limit": limit})

    @router.get("/misc")
    async def misc(self) -> HTMLResponse:
        """GET: Render misc page with counter value."""
        counter = self.core.services.misc.counter.get()
        return await self.render.html("misc.j2", zero=0, counter=counter)

    @router.get("/performance-dropdown-html")
    async def performance_dropdown_html(self) -> HTMLResponse:
        """GET: Render page with 1000-item dropdown for performance testing."""
        rows = list(range(1000))
        return await self.render.html("performance_dropdown_html.j2", rows=rows)


@cbv(router)
class ActionRouter(AppView):
    """Form action endpoints with redirects."""

    @router.post("/data/{id}/inc")
    async def inc_data(self, id: ObjectId, value: Annotated[int, Form()]) -> RedirectResponse:
        """POST: Increment data value via form and redirect to /data."""
        await self.core.db.data.update_one({"_id": id}, {"$inc": {"value": value}})
        self.render.flash(f"Data {id} incremented by {value}")
        return redirect("/data")
