"""Orders defpage setup — registers layouts, page helpers, and loads .sx pages."""
from __future__ import annotations

from typing import Any


def setup_orders_pages() -> None:
    """Register orders-specific layouts, page helpers, and load page definitions."""
    _register_orders_layouts()
    _register_orders_helpers()
    _load_orders_page_files()


def _load_orders_page_files() -> None:
    """Load defpage definitions from orders/sxc/pages/*.sx."""
    import os
    from shared.sx.pages import load_page_dir
    load_page_dir(os.path.dirname(__file__), "orders")


# ---------------------------------------------------------------------------
# Layouts
# ---------------------------------------------------------------------------

def _register_orders_layouts() -> None:
    from shared.sx.layouts import register_custom_layout
    register_custom_layout("orders", _orders_full, _orders_oob, _orders_mobile)
    register_custom_layout("order-detail", _order_detail_full, _order_detail_oob, _order_detail_mobile)


def _orders_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, header_child_sx
    from sx.sx_components import _auth_header_sx, _orders_header_sx

    list_url = kw.get("list_url", "/")
    root_hdr = root_header_sx(ctx)
    inner = "(<> " + _auth_header_sx(ctx) + " " + _orders_header_sx(ctx, list_url) + ")"
    return "(<> " + root_hdr + " " + header_child_sx(inner) + ")"


def _orders_oob(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, sx_call, SxExpr
    from sx.sx_components import _auth_header_sx, _orders_header_sx

    list_url = kw.get("list_url", "/")
    auth_hdr = _auth_header_sx(ctx, oob=True)
    auth_child_oob = sx_call("oob-header-sx",
                             parent_id="auth-header-child",
                             row=SxExpr(_orders_header_sx(ctx, list_url)))
    root_hdr = root_header_sx(ctx, oob=True)
    return "(<> " + auth_hdr + " " + auth_child_oob + " " + root_hdr + ")"


def _orders_mobile(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import mobile_menu_sx, mobile_root_nav_sx
    return mobile_menu_sx(mobile_root_nav_sx(ctx))


def _order_detail_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, sx_call, SxExpr
    from sx.sx_components import _auth_header_sx, _orders_header_sx

    list_url = kw.get("list_url", "/")
    detail_url = kw.get("detail_url", "/")
    root_hdr = root_header_sx(ctx)
    order_row = sx_call(
        "menu-row-sx",
        id="order-row", level=3, colour="sky", link_href=detail_url,
        link_label="Order", icon="fa fa-gbp",
    )
    detail_header = sx_call(
        "order-detail-header-stack",
        auth=SxExpr(_auth_header_sx(ctx)),
        orders=SxExpr(_orders_header_sx(ctx, list_url)),
        order=SxExpr(order_row),
    )
    return "(<> " + root_hdr + " " + detail_header + ")"


def _order_detail_oob(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, sx_call, SxExpr

    detail_url = kw.get("detail_url", "/")
    order_row_oob = sx_call(
        "menu-row-sx",
        id="order-row", level=3, colour="sky", link_href=detail_url,
        link_label="Order", icon="fa fa-gbp", oob=True,
    )
    header_child_oob = sx_call("oob-header-sx",
                               parent_id="orders-header-child",
                               row=SxExpr(order_row_oob))
    root_hdr = root_header_sx(ctx, oob=True)
    return "(<> " + header_child_oob + " " + root_hdr + ")"


def _order_detail_mobile(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import mobile_menu_sx, mobile_root_nav_sx
    return mobile_menu_sx(mobile_root_nav_sx(ctx))


# ---------------------------------------------------------------------------
# Page helpers — Python functions callable from defpage expressions
# ---------------------------------------------------------------------------

def _register_orders_helpers() -> None:
    from shared.sx.pages import register_page_helpers

    register_page_helpers("orders", {
        # Orders list
        "orders-list-content": _h_orders_list_content,
        "orders-list-filter": _h_orders_list_filter,
        "orders-list-aside": _h_orders_list_aside,
        "orders-list-url": _h_orders_list_url,
        # Order detail
        "order-detail-content": _h_order_detail_content,
        "order-detail-filter": _h_order_detail_filter,
        "order-detail-url": _h_order_detail_url,
        "order-list-url-from-detail": _h_order_list_url_from_detail,
    })


def _h_orders_list_content():
    from quart import g
    d = getattr(g, "orders_page_data", None)
    if not d:
        from shared.sx.helpers import sx_call
        return sx_call("order-empty-state")
    from sx.sx_components import _orders_rows_sx, _orders_main_panel_sx
    rows = _orders_rows_sx(d["orders"], d["page"], d["total_pages"],
                           d["url_for_fn"], d["qs_fn"])
    return _orders_main_panel_sx(d["orders"], rows)


def _h_orders_list_filter():
    from quart import g
    from shared.sx.helpers import sx_call, SxExpr
    from shared.sx.page import SEARCH_HEADERS_MOBILE
    d = getattr(g, "orders_page_data", None)
    search = d.get("search", "") if d else ""
    search_count = d.get("search_count", "") if d else ""
    search_mobile = sx_call("search-mobile",
        current_local_href="/",
        search=search or "",
        search_count=search_count or "",
        hx_select="#main-panel",
        search_headers_mobile=SEARCH_HEADERS_MOBILE,
    )
    return sx_call("order-list-header", search_mobile=SxExpr(search_mobile))


def _h_orders_list_aside():
    from quart import g
    from shared.sx.helpers import sx_call
    from shared.sx.page import SEARCH_HEADERS_DESKTOP
    d = getattr(g, "orders_page_data", None)
    search = d.get("search", "") if d else ""
    search_count = d.get("search_count", "") if d else ""
    return sx_call("search-desktop",
        current_local_href="/",
        search=search or "",
        search_count=search_count or "",
        hx_select="#main-panel",
        search_headers_desktop=SEARCH_HEADERS_DESKTOP,
    )


def _h_orders_list_url():
    from quart import g
    d = getattr(g, "orders_page_data", None)
    return d["list_url"] if d else "/"


def _h_order_detail_content():
    from quart import g
    d = getattr(g, "order_detail_data", None)
    if not d:
        return ""
    from sx.sx_components import _order_main_sx
    return _order_main_sx(d["order"], d["calendar_entries"])


def _h_order_detail_filter():
    from quart import g
    d = getattr(g, "order_detail_data", None)
    if not d:
        return ""
    from sx.sx_components import _order_filter_sx
    return _order_filter_sx(d["order"], d["list_url"], d["recheck_url"],
                            d["pay_url"], d["csrf_token"])


def _h_order_detail_url():
    from quart import g
    d = getattr(g, "order_detail_data", None)
    return d["detail_url"] if d else "/"


def _h_order_list_url_from_detail():
    from quart import g
    d = getattr(g, "order_detail_data", None)
    return d["list_url"] if d else "/"
