"""Cart defpage setup — registers layouts and loads .sx pages."""
from __future__ import annotations

from typing import Any

from markupsafe import escape
from shared.sx.parser import SxExpr


def setup_cart_pages() -> None:
    """Register cart-specific layouts and load page definitions."""
    _register_cart_layouts()
    _load_cart_page_files()


def _load_cart_page_files() -> None:
    import os
    from shared.sx.pages import load_page_dir
    load_page_dir(os.path.dirname(__file__), "cart")


# ---------------------------------------------------------------------------
# Header helpers (still needed by layouts and render functions)
# ---------------------------------------------------------------------------

def _ensure_post_ctx(ctx: dict, page_post: Any) -> dict:
    """Ensure ctx has a 'post' dict from page_post DTO."""
    if ctx.get("post") or not page_post:
        return ctx
    return {**ctx, "post": {
        "id": getattr(page_post, "id", None),
        "slug": getattr(page_post, "slug", ""),
        "title": getattr(page_post, "title", ""),
        "feature_image": getattr(page_post, "feature_image", None),
    }}


async def _ensure_container_nav(ctx: dict) -> dict:
    """Fetch container_nav if not already present."""
    if ctx.get("container_nav"):
        return ctx
    post = ctx.get("post") or {}
    post_id = post.get("id")
    if not post_id:
        return ctx
    slug = post.get("slug", "")
    from shared.infrastructure.fragments import fetch_fragments
    nav_params = {
        "container_type": "page",
        "container_id": str(post_id),
        "post_slug": slug,
    }
    events_nav, market_nav = await fetch_fragments([
        ("events", "container-nav", nav_params),
        ("market", "container-nav", nav_params),
    ], required=False)
    return {**ctx, "container_nav": events_nav + market_nav}


async def _post_header_sx(ctx: dict, page_post: Any, *, oob: bool = False) -> str:
    from shared.sx.helpers import post_header_sx as _shared_post_header_sx
    ctx = _ensure_post_ctx(ctx, page_post)
    ctx = await _ensure_container_nav(ctx)
    return await _shared_post_header_sx(ctx, oob=oob)


async def _cart_header_sx(ctx: dict, *, oob: bool = False) -> str:
    from shared.sx.helpers import render_to_sx, call_url
    return await render_to_sx(
        "menu-row-sx",
        id="cart-row", level=1, colour="sky",
        link_href=call_url(ctx, "cart_url", "/"),
        link_label="cart", icon="fa fa-shopping-cart",
        child_id="cart-header-child", oob=oob,
    )


async def _page_cart_header_sx(ctx: dict, page_post: Any, *, oob: bool = False) -> str:
    from shared.sx.helpers import render_to_sx, call_url
    slug = page_post.slug if page_post else ""
    title = ((page_post.title if page_post else None) or "")[:160]
    label_parts = []
    if page_post and page_post.feature_image:
        label_parts.append(await render_to_sx("cart-page-label-img", src=page_post.feature_image))
    label_parts.append(f'(span "{escape(title)}")')
    label_sx = "(<> " + " ".join(label_parts) + ")"
    nav_sx = await render_to_sx("cart-all-carts-link", href=call_url(ctx, "cart_url", "/"))
    return await render_to_sx(
        "menu-row-sx",
        id="page-cart-row", level=2, colour="sky",
        link_href=call_url(ctx, "cart_url", f"/{slug}/"),
        link_label_content=SxExpr(label_sx),
        nav=SxExpr(nav_sx), oob=oob,
    )


# ---------------------------------------------------------------------------
# Order serialization helpers
# ---------------------------------------------------------------------------

def _serialize_order(order: Any) -> dict:
    from shared.infrastructure.urls import market_product_url
    created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
    items = []
    if order.items:
        for item in order.items:
            items.append({
                "product_image": item.product_image,
                "product_title": item.product_title or "Unknown product",
                "product_id": item.product_id,
                "product_slug": item.product_slug,
                "product_url": market_product_url(item.product_slug),
                "quantity": item.quantity,
                "unit_price_formatted": f"{item.unit_price or 0:.2f}",
                "currency": item.currency or order.currency or "GBP",
            })
    return {
        "id": order.id,
        "status": order.status or "pending",
        "created_at_formatted": created,
        "description": order.description or "",
        "total_formatted": f"{order.total_amount or 0:.2f}",
        "total_amount": float(order.total_amount or 0),
        "currency": order.currency or "GBP",
        "items": items,
    }


def _serialize_calendar_entry(e: Any) -> dict:
    st = e.state or ""
    ds = e.start_at.strftime("%-d %b %Y, %H:%M") if e.start_at else ""
    if e.end_at:
        ds += f" \u2013 {e.end_at.strftime('%-d %b %Y, %H:%M')}"
    return {"name": e.name, "state": st, "date_str": ds, "cost_formatted": f"{e.cost or 0:.2f}"}


# ---------------------------------------------------------------------------
# Render functions (called by routes) — delegate header composition to .sx
# ---------------------------------------------------------------------------

async def render_orders_page(ctx, orders, page, total_pages, search, search_count, url_for_fn, qs_fn):
    from shared.sx.helpers import render_to_sx, render_to_sx_with_env, _ctx_to_env, search_desktop_sx, search_mobile_sx, full_page_sx
    from shared.utils import route_prefix
    ctx["search"] = search
    ctx["search_count"] = search_count
    pfx = route_prefix()
    list_url = pfx + url_for_fn("orders.list_orders")
    detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
    order_dicts = [_serialize_order(o) for o in orders]
    content = await render_to_sx("orders-list-content", orders=order_dicts,
        page=page, total_pages=total_pages, rows_url=list_url, detail_url_prefix=detail_url_prefix)
    header_rows = await render_to_sx_with_env("cart-orders-layout-full", _ctx_to_env(ctx),
        list_url=list_url,
    )
    filt = await render_to_sx("order-list-header", search_mobile=SxExpr(await search_mobile_sx(ctx)))
    return await full_page_sx(ctx, header_rows=header_rows, filter=filt,
                          aside=await search_desktop_sx(ctx), content=content)


async def render_orders_rows(ctx, orders, page, total_pages, url_for_fn, qs_fn):
    from shared.sx.helpers import render_to_sx
    from shared.utils import route_prefix
    pfx = route_prefix()
    list_url = pfx + url_for_fn("orders.list_orders")
    detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
    order_dicts = [_serialize_order(o) for o in orders]
    parts = []
    for od in order_dicts:
        parts.append(await render_to_sx("order-row-pair", order=od, detail_url_prefix=detail_url_prefix))
    next_scroll = ""
    if page < total_pages:
        next_url = list_url + qs_fn(page=page + 1)
        next_scroll = await render_to_sx("infinite-scroll", url=next_url, page=page,
            total_pages=total_pages, id_prefix="orders", colspan=5)
    else:
        next_scroll = await render_to_sx("order-end-row")
    return await render_to_sx("cart-orders-rows",
        rows=SxExpr("(<> " + " ".join(parts) + ")"),
        next_scroll=SxExpr(next_scroll),
    )


async def render_orders_oob(ctx, orders, page, total_pages, search, search_count, url_for_fn, qs_fn):
    from shared.sx.helpers import render_to_sx, render_to_sx_with_env, _ctx_to_env, search_desktop_sx, search_mobile_sx, oob_page_sx
    from shared.utils import route_prefix
    ctx["search"] = search
    ctx["search_count"] = search_count
    pfx = route_prefix()
    list_url = pfx + url_for_fn("orders.list_orders")
    detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
    order_dicts = [_serialize_order(o) for o in orders]
    content = await render_to_sx("orders-list-content", orders=order_dicts,
        page=page, total_pages=total_pages, rows_url=list_url, detail_url_prefix=detail_url_prefix)
    oobs = await render_to_sx_with_env("cart-orders-layout-oob", _ctx_to_env(ctx, oob=True),
        list_url=list_url,
    )
    filt = await render_to_sx("order-list-header", search_mobile=SxExpr(await search_mobile_sx(ctx)))
    return await oob_page_sx(oobs=oobs, filter=filt, aside=await search_desktop_sx(ctx), content=content)


async def render_order_page(ctx, order, calendar_entries, url_for_fn):
    from shared.sx.helpers import render_to_sx, render_to_sx_with_env, _ctx_to_env, full_page_sx
    from shared.utils import route_prefix
    from shared.browser.app.csrf import generate_csrf_token
    pfx = route_prefix()
    detail_url = pfx + url_for_fn("orders.order.order_detail", order_id=order.id)
    list_url = pfx + url_for_fn("orders.list_orders")
    recheck_url = pfx + url_for_fn("orders.order.order_recheck", order_id=order.id)
    pay_url = pfx + url_for_fn("orders.order.order_pay", order_id=order.id)
    order_data = _serialize_order(order)
    cal_data = [_serialize_calendar_entry(e) for e in (calendar_entries or [])]
    main = await render_to_sx("order-detail-content", order=order_data, calendar_entries=cal_data)
    filt = await render_to_sx("order-detail-filter-content", order=order_data,
        list_url=list_url, recheck_url=recheck_url, pay_url=pay_url, csrf=generate_csrf_token())
    header_rows = await render_to_sx_with_env("cart-order-detail-layout-full", _ctx_to_env(ctx),
        list_url=list_url, detail_url=detail_url,
        order_label=f"Order {order.id}",
    )
    return await full_page_sx(ctx, header_rows=header_rows, filter=filt, content=main)


async def render_order_oob(ctx, order, calendar_entries, url_for_fn):
    from shared.sx.helpers import render_to_sx, render_to_sx_with_env, _ctx_to_env, oob_page_sx
    from shared.utils import route_prefix
    from shared.browser.app.csrf import generate_csrf_token
    pfx = route_prefix()
    detail_url = pfx + url_for_fn("orders.order.order_detail", order_id=order.id)
    list_url = pfx + url_for_fn("orders.list_orders")
    recheck_url = pfx + url_for_fn("orders.order.order_recheck", order_id=order.id)
    pay_url = pfx + url_for_fn("orders.order.order_pay", order_id=order.id)
    order_data = _serialize_order(order)
    cal_data = [_serialize_calendar_entry(e) for e in (calendar_entries or [])]
    main = await render_to_sx("order-detail-content", order=order_data, calendar_entries=cal_data)
    filt = await render_to_sx("order-detail-filter-content", order=order_data,
        list_url=list_url, recheck_url=recheck_url, pay_url=pay_url, csrf=generate_csrf_token())
    oobs = await render_to_sx_with_env("cart-order-detail-layout-oob", _ctx_to_env(ctx, oob=True),
        detail_url=detail_url,
        order_label=f"Order {order.id}",
    )
    return await oob_page_sx(oobs=oobs, filter=filt, content=main)


async def render_checkout_error_page(ctx, error=None, order=None):
    from shared.sx.helpers import render_to_sx, render_to_sx_with_env, _ctx_to_env, full_page_sx
    from shared.infrastructure.urls import cart_url
    err_msg = error or "Unexpected error while creating the hosted checkout session."
    order_sx = await render_to_sx("checkout-error-order-id", oid=f"#{order.id}") if order else None
    hdr = await render_to_sx_with_env("layout-root-full", _ctx_to_env(ctx))
    filt = await render_to_sx("checkout-error-header")
    content = await render_to_sx("checkout-error-content", msg=err_msg,
        order=SxExpr(order_sx) if order_sx else None, back_url=cart_url("/"))
    return await full_page_sx(ctx, header_rows=hdr, filter=filt, content=content)


async def render_cart_payments_panel(ctx):
    from shared.sx.helpers import render_to_sx
    page_config = ctx.get("page_config")
    pc_data = None
    if page_config:
        pc_data = {
            "sumup_api_key": bool(getattr(page_config, "sumup_api_key", None)),
            "sumup_merchant_code": getattr(page_config, "sumup_merchant_code", None) or "",
            "sumup_checkout_prefix": getattr(page_config, "sumup_checkout_prefix", None) or "",
        }
    return await render_to_sx("cart-payments-content", page_config=pc_data)


# ---------------------------------------------------------------------------
# Layouts — thin wrappers delegating to .sx defcomps in cart/sx/layouts.sx
# ---------------------------------------------------------------------------

def _register_cart_layouts() -> None:
    from shared.sx.layouts import register_custom_layout
    register_custom_layout("cart-page", _cart_page_full, _cart_page_oob)
    register_custom_layout("cart-admin", _cart_admin_full, _cart_admin_oob)


async def _cart_page_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import render_to_sx_with_env, _ctx_to_env
    page_post = ctx.get("page_post")
    env = _ctx_to_env(ctx)
    return await render_to_sx_with_env("cart-page-layout-full", env,
        cart_row=SxExpr(await _cart_header_sx(ctx)),
        page_cart_row=SxExpr(await _page_cart_header_sx(ctx, page_post)),
    )


async def _cart_page_oob(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import render_to_sx_with_env, _ctx_to_env, root_header_sx
    page_post = ctx.get("page_post")
    env = _ctx_to_env(ctx, oob=True)
    return await render_to_sx_with_env("cart-page-layout-oob", env,
        root_header_oob=SxExpr(await root_header_sx(ctx, oob=True)),
        cart_row_oob=SxExpr(await _cart_header_sx(ctx, oob=True)),
        page_cart_row=SxExpr(await _page_cart_header_sx(ctx, page_post)),
    )


async def _cart_admin_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import render_to_sx_with_env, _ctx_to_env
    page_post = ctx.get("page_post")
    selected = kw.get("selected", "")
    env = _ctx_to_env(ctx)
    return await render_to_sx_with_env("cart-admin-layout-full", env,
        post_header=SxExpr(await _post_header_sx(ctx, page_post)),
        admin_header=SxExpr(await _cart_page_admin_header_sx(ctx, page_post, selected=selected)),
    )


async def _cart_admin_oob(ctx: dict, **kw: Any) -> str:
    page_post = ctx.get("page_post")
    selected = kw.get("selected", "")
    return await _cart_page_admin_header_sx(ctx, page_post, oob=True, selected=selected)


async def _cart_page_admin_header_sx(ctx: dict, page_post: Any, *, oob: bool = False,
                                  selected: str = "") -> str:
    from shared.sx.helpers import post_admin_header_sx
    slug = page_post.slug if page_post else ""
    ctx = _ensure_post_ctx(ctx, page_post)
    return await post_admin_header_sx(ctx, slug, oob=oob, selected=selected)
