from __future__ import annotations

import re
import unicodedata

from quart import make_response, request, g, Blueprint

from shared.browser.app.authz import require_admin
from shared.services.registry import services
from shared.sx.helpers import sx_response


def _slugify(value: str, max_len: int = 255) -> str:
    if value is None:
        value = ""
    value = unicodedata.normalize("NFKD", value)
    value = value.encode("ascii", "ignore").decode("ascii")
    value = value.lower()
    value = value.replace("/", "-")
    value = re.sub(r"[^a-z0-9]+", "-", value)
    value = re.sub(r"-{2,}", "-", value)
    value = value.strip("-")[:max_len].strip("-")
    return value or "market"


def register():
    bp = Blueprint("page_admin", __name__)

    @bp.post("/new/")
    @require_admin
    async def create_market(**kwargs):
        form = await request.form
        name = (form.get("name") or "").strip()

        post_data = getattr(g, "post_data", None)
        post_id = (post_data.get("post") or {}).get("id") if post_data else None

        if not post_id:
            return await make_response("No page context", 400)

        slug = _slugify(name)

        try:
            await services.market.create_marketplace(g.s, "page", post_id, name, slug)
        except Exception as e:
            from shared.sx.jinja_bridge import render as render_comp
            return await make_response(render_comp("error-inline", message=str(e)), 422)

        from shared.sx.page import get_template_context
        from sxc.pages.renders import render_markets_admin_list_panel
        ctx = await get_template_context()
        html = await render_markets_admin_list_panel(ctx)
        return sx_response(html)

    @bp.delete("/<market_slug>/")
    @require_admin
    async def delete_market(**kwargs):
        market_slug = g.get("market_slug", "")
        post_data = getattr(g, "post_data", None)
        post_id = (post_data.get("post") or {}).get("id") if post_data else None

        if not post_id:
            return await make_response("No page context", 400)

        await services.market.soft_delete_marketplace(g.s, "page", post_id, market_slug)

        from shared.sx.page import get_template_context
        from sxc.pages.renders import render_markets_admin_list_panel
        ctx = await get_template_context()
        html = await render_markets_admin_list_panel(ctx)
        return sx_response(html)

    return bp
