from __future__ import annotations

from quart import Blueprint, make_response, request, jsonify, g, url_for

from shared.browser.app.authz import require_admin
from .services.menu_items import (
    get_all_menu_items,
    get_menu_item_by_id,
    create_menu_item,
    update_menu_item,
    delete_menu_item,
    search_pages,
    MenuItemError,
)
from markupsafe import escape
from shared.sx.helpers import sx_response, sx_call
from shared.sx.parser import SxExpr
from shared.browser.app.csrf import generate_csrf_token


def _render_menu_items_list(menu_items):
    """Serialize ORM menu items and render via .sx defcomp."""
    csrf = generate_csrf_token()
    items = []
    for item in menu_items:
        items.append({
            "feature_image": getattr(item, "feature_image", None),
            "label": getattr(item, "label", "") or "",
            "url": getattr(item, "url", "") or "",
            "sort_order": getattr(item, "position", 0) or 0,
            "edit_url": url_for("menu_items.edit_menu_item", item_id=item.id),
            "delete_url": url_for("menu_items.delete_menu_item_route", item_id=item.id),
        })
    new_url = url_for("menu_items.new_menu_item")
    return sx_call("blog-menu-items-content",
                    menu_items=items, new_url=new_url, csrf=csrf)


def _render_menu_item_form(menu_item=None) -> str:
    """Render menu item add/edit form."""
    csrf = generate_csrf_token()
    search_url = url_for("menu_items.search_pages_route")
    is_edit = menu_item is not None

    if is_edit:
        action_url = url_for("menu_items.update_menu_item_route", item_id=menu_item.id)
        action_attr = f'sx-put="{action_url}"'
        post_id = str(menu_item.container_id) if menu_item.container_id else ""
        label = getattr(menu_item, "label", "") or ""
        slug = getattr(menu_item, "slug", "") or ""
        fi = getattr(menu_item, "feature_image", None) or ""
    else:
        action_url = url_for("menu_items.create_menu_item_route")
        action_attr = f'sx-post="{action_url}"'
        post_id = ""
        label = ""
        slug = ""
        fi = ""

    if post_id:
        img_html = (f'<img src="{fi}" alt="{label}" class="w-10 h-10 rounded-full object-cover" />'
                    if fi else '<div class="w-10 h-10 rounded-full bg-stone-200"></div>')
        selected = (f'<div id="selected-page-display" class="mb-3 p-3 bg-stone-50 rounded flex items-center gap-3">'
                    f'{img_html}<div class="flex-1"><div class="font-medium">{label}</div>'
                    f'<div class="text-xs text-stone-500">{slug}</div></div></div>')
    else:
        selected = '<div id="selected-page-display" class="mb-3 hidden"></div>'

    close_js = "document.getElementById('menu-item-form').innerHTML = ''"
    title = "Edit Menu Item" if is_edit else "Add Menu Item"

    html = f'''<div class="bg-white rounded-lg shadow p-6 mb-6" id="menu-item-form-container">
  <div class="flex justify-between items-center mb-4">
    <h2 class="text-xl font-semibold">{title}</h2>
    <button type="button" onclick="{close_js}" class="text-stone-400 hover:text-stone-600">
      <i class="fa fa-times"></i></button>
  </div>
  <input type="hidden" name="post_id" id="selected-post-id" value="{post_id}" />
  {selected}
  <form {action_attr} sx-target="#menu-items-list" sx-swap="innerHTML"
    sx-include="#selected-post-id"
    sx-on:afterRequest="if(event.detail.successful) {{ {close_js} }}"
    class="space-y-4">
    <input type="hidden" name="csrf_token" value="{csrf}">
    <div class="flex gap-2 pb-3 border-b">
      <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
        <i class="fa fa-save"></i> Save</button>
      <button type="button" onclick="{close_js}"
        class="px-4 py-2 border border-stone-300 rounded hover:bg-stone-50">Cancel</button>
    </div>
  </form>
  <div class="mt-4">
    <label class="block text-sm font-medium text-stone-700 mb-2">Select Page</label>
    <input type="text" placeholder="Search for a page... (or leave blank for all)"
      sx-get="{search_url}" sx-trigger="keyup changed delay:300ms, focus once"
      sx-target="#page-search-results" sx-swap="innerHTML"
      name="q" id="page-search-input"
      class="w-full px-3 py-2 border border-stone-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
    <div id="page-search-results" class="mt-2"></div>
  </div>
</div>
<script>
document.addEventListener('click', function(e) {{
  var pageOption = e.target.closest('[data-page-id]');
  if (pageOption) {{
    var postId = pageOption.dataset.pageId;
    var postTitle = pageOption.dataset.pageTitle;
    var postSlug = pageOption.dataset.pageSlug;
    var postImage = pageOption.dataset.pageImage;
    document.getElementById('selected-post-id').value = postId;
    var display = document.getElementById('selected-page-display');
    display.innerHTML = '<div class="p-3 bg-stone-50 rounded flex items-center gap-3">' +
      (postImage ? '<img src="' + postImage + '" alt="' + postTitle + '" class="w-10 h-10 rounded-full object-cover" />' : '<div class="w-10 h-10 rounded-full bg-stone-200"></div>') +
      '<div class="flex-1"><div class="font-medium">' + postTitle + '</div><div class="text-xs text-stone-500">' + postSlug + '</div></div></div>';
    display.classList.remove('hidden');
    document.getElementById('page-search-results').innerHTML = '';
  }}
}});
</script>'''
    return html


def _render_page_search_results(pages, query, page, has_more) -> str:
    """Render page search results."""
    if not pages and query:
        return sx_call("page-search-empty", query=query)
    if not pages:
        return ""

    items = []
    for post in pages:
        items.append(sx_call("page-search-item",
                             id=post.id, title=post.title,
                             slug=post.slug,
                             feature_image=post.feature_image or None))

    sentinel = ""
    if has_more:
        search_url = url_for("menu_items.search_pages_route")
        sentinel = sx_call("page-search-sentinel",
                          url=search_url, query=query,
                          next_page=page + 1)

    items_sx = "(<> " + " ".join(items) + ")"
    return sx_call("page-search-results",
                   items=SxExpr(items_sx),
                   sentinel=sentinel or None)


def _render_menu_items_nav_oob(menu_items) -> str:
    """Render OOB nav update for menu items."""
    from quart import request as qrequest

    if not menu_items:
        return sx_call("blog-nav-empty", wrapper_id="menu-items-nav-wrapper")

    first_seg = qrequest.path.strip("/").split("/")[0] if qrequest else ""

    select_colours = (
        "[.hover-capable_&]:hover:bg-yellow-300"
        " aria-selected:bg-stone-500 aria-selected:text-white"
        " [.hover-capable_&[aria-selected=true]:hover]:bg-orange-500"
    )
    nav_button_cls = (
        f"justify-center cursor-pointer flex flex-row items-center gap-2"
        f" rounded bg-stone-200 text-black {select_colours} p-3"
    )

    container_id = "menu-items-container"
    arrow_cls = f"scrolling-menu-arrow-{container_id}"

    scroll_hs = (
        f"on load or scroll"
        f" if window.innerWidth >= 640 and my.scrollWidth > my.clientWidth"
        f" remove .hidden from .{arrow_cls} add .flex to .{arrow_cls}"
        f" else add .hidden to .{arrow_cls} remove .flex from .{arrow_cls} end"
    )

    item_parts = []
    for item in menu_items:
        item_slug = getattr(item, "slug", "") if hasattr(item, "slug") else item.get("slug", "")
        label = getattr(item, "label", "") if hasattr(item, "label") else item.get("label", "")
        fi = getattr(item, "feature_image", None) if hasattr(item, "feature_image") else item.get("feature_image")

        href = f"/{item_slug}/"
        selected = "true" if item_slug == first_seg else "false"

        img_sx = sx_call("img-or-placeholder", src=fi, alt=label,
            size_cls="w-8 h-8 rounded-full object-cover flex-shrink-0")

        if item_slug != "cart":
            item_parts.append(sx_call("blog-nav-item-link",
                href=href, hx_get=f"/{item_slug}/", selected=selected,
                nav_cls=nav_button_cls, img=img_sx, label=label,
            ))
        else:
            item_parts.append(sx_call("blog-nav-item-plain",
                href=href, selected=selected, nav_cls=nav_button_cls,
                img=img_sx, label=label,
            ))

    items_sx = "(<> " + " ".join(item_parts) + ")" if item_parts else ""

    return sx_call("scroll-nav-wrapper",
        wrapper_id="menu-items-nav-wrapper", container_id=container_id,
        arrow_cls=arrow_cls,
        left_hs=f"on click set #{container_id}.scrollLeft to #{container_id}.scrollLeft - 200",
        scroll_hs=scroll_hs,
        right_hs=f"on click set #{container_id}.scrollLeft to #{container_id}.scrollLeft + 200",
        items=SxExpr(items_sx) if items_sx else None, oob=True,
    )


def register():
    bp = Blueprint("menu_items", __name__, url_prefix='/settings/menu_items')

    def get_menu_items_nav_oob_sync(menu_items):
        """Helper to generate OOB update for root nav menu items"""
        return _render_menu_items_nav_oob(menu_items)

    @bp.get("/new/")
    @require_admin
    async def new_menu_item():
        """Show form to create new menu item"""
        return sx_response(_render_menu_item_form())

    @bp.post("/")
    @require_admin
    async def create_menu_item_route():
        """Create a new menu item"""
        form = await request.form
        post_id = form.get("post_id")

        if not post_id:
            return jsonify({"message": "Page is required", "errors": {"post_id": ["Please select a page"]}}), 422

        try:
            post_id = int(post_id)
        except ValueError:
            return jsonify({"message": "Invalid page ID", "errors": {"post_id": ["Invalid page"]}}), 422

        try:
            menu_item = await create_menu_item(g.s, post_id)
            await g.s.flush()

            # Get updated list and nav OOB
            menu_items = await get_all_menu_items(g.s)
            html = _render_menu_items_list(menu_items)
            nav_oob = get_menu_items_nav_oob_sync(menu_items)
            return sx_response(html + nav_oob)

        except MenuItemError as e:
            return jsonify({"message": str(e), "errors": {}}), 400

    @bp.get("/<int:item_id>/edit/")
    @require_admin
    async def edit_menu_item(item_id: int):
        """Show form to edit menu item"""
        menu_item = await get_menu_item_by_id(g.s, item_id)
        if not menu_item:
            return await make_response("Menu item not found", 404)

        return sx_response(_render_menu_item_form(menu_item=menu_item))

    @bp.put("/<int:item_id>/")
    @require_admin
    async def update_menu_item_route(item_id: int):
        """Update a menu item"""
        form = await request.form
        post_id = form.get("post_id")

        if not post_id:
            return jsonify({"message": "Page is required", "errors": {"post_id": ["Please select a page"]}}), 422

        try:
            post_id = int(post_id)
        except ValueError:
            return jsonify({"message": "Invalid page ID", "errors": {"post_id": ["Invalid page"]}}), 422

        try:
            menu_item = await update_menu_item(g.s, item_id, post_id=post_id)
            await g.s.flush()

            # Get updated list and nav OOB
            menu_items = await get_all_menu_items(g.s)
            html = _render_menu_items_list(menu_items)
            nav_oob = get_menu_items_nav_oob_sync(menu_items)
            return sx_response(html + nav_oob)

        except MenuItemError as e:
            return jsonify({"message": str(e), "errors": {}}), 400

    @bp.delete("/<int:item_id>/")
    @require_admin
    async def delete_menu_item_route(item_id: int):
        """Delete a menu item"""
        success = await delete_menu_item(g.s, item_id)

        if not success:
            return await make_response("Menu item not found", 404)

        await g.s.flush()

        # Get updated list and nav OOB
        menu_items = await get_all_menu_items(g.s)
        html = _render_menu_items_list(menu_items)
        nav_oob = get_menu_items_nav_oob_sync(menu_items)
        return sx_response(html + nav_oob)

    @bp.get("/pages/search/")
    @require_admin
    async def search_pages_route():
        """Search for pages to add as menu items"""
        query = request.args.get("q", "").strip()
        page = int(request.args.get("page", 1))
        per_page = 10

        pages, total = await search_pages(g.s, query, page, per_page)
        has_more = (page * per_page) < total

        return sx_response(_render_page_search_results(pages, query, page, has_more))

    @bp.post("/reorder/")
    @require_admin
    async def reorder_menu_items_route():
        """Reorder menu items"""
        from .services.menu_items import reorder_menu_items

        form = await request.form
        item_ids_str = form.get("item_ids", "")

        if not item_ids_str:
            return jsonify({"message": "No items to reorder", "errors": {}}), 400

        try:
            item_ids = [int(id.strip()) for id in item_ids_str.split(",") if id.strip()]
        except ValueError:
            return jsonify({"message": "Invalid item IDs", "errors": {}}), 400

        await reorder_menu_items(g.s, item_ids)
        await g.s.flush()

        # Get updated list and nav OOB
        menu_items = await get_all_menu_items(g.s)
        html = _render_menu_items_list(menu_items)
        nav_oob = get_menu_items_nav_oob_sync(menu_items)
        return sx_response(html + nav_oob)

    return bp
