"""Обработчик главного меню."""
import asyncio

from maxapi.context import BaseContext
from maxapi.dispatcher import Router
from maxapi.filters import F
from maxapi.types.updates.message_callback import MessageCallback

from bot.keyboards import main_menu_kb
from bot.send_helper import bot_reply
from database.queries.organizations import get_organization
from external.intradesk_api import count_client_open_tasks, get_client_last_comment

router = Router(router_id="menu")


async def build_main_menu_text(bot_user: dict) -> str:
    """Формирует текст главного меню — данные берутся из Intradesk API."""
    org_id = bot_user.get("org_id")
    org_name: str | None = None
    intradesk_id: int | None = None

    if org_id:
        org = await get_organization(org_id)
        org_name = org["name"] if org else None
        intradesk_id = org.get("intradesk_id") if org else None

    lines: list[str] = []
    lines.append(f"🏢  {org_name}" if org_name else "🏠  Поддержка")
    lines.append("━" * 16)

    if intradesk_id:
        # Счётчик активных и последний комментарий — параллельно
        active, last_comment = await asyncio.gather(
            count_client_open_tasks(intradesk_id),
            get_client_last_comment(intradesk_id),
        )

        if active == 0:
            lines += [
                "📭 Активных заявок нет",
                "",
                "Нажмите «Создать заявку» и мы",
                "свяжемся с вами в ближайшее время.",
            ]
        else:
            lines.append(f"📋 Активных заявок: {active}")

            if last_comment and last_comment.get("text"):
                ctext = last_comment["text"]
                if len(ctext) > 120:
                    ctext = ctext[:120] + "…"
                raw_date = last_comment.get("date") or ""
                # raw_date приходит как "2026-03-26 11:54"
                date_part = raw_date[:10]
                time_part = raw_date[11:16] if len(raw_date) >= 16 else ""
                if len(date_part) == 10:
                    y, m, d = date_part.split("-")
                    short_date = f"{d}.{m}" + (f" {time_part}" if time_part else "")
                else:
                    short_date = raw_date
                author = (last_comment.get("author") or "").strip()
                task_num = last_comment.get("task_number")
                num_str = f" (заявка #{task_num})" if task_num else ""
                lines += [
                    "",
                    f"💬 Последний ответ{num_str}:",
                    f"«{ctext}»",
                    f"— {author}, {short_date}",
                ]
            else:
                lines += ["", "💬 Новых ответов нет"]
    else:
        lines.append("📭 Нет данных об организации")

    lines += ["", "━" * 16, "Выберите действие 👇"]
    return "\n".join(lines)


@router.message_callback(F.callback.payload == "main_menu")
async def cb_main_menu(
    event: MessageCallback, context: BaseContext, bot_user: dict
) -> None:
    from bot.handlers.create_ticket import cleanup_ticket_flow
    await cleanup_ticket_flow(event.bot, context)
    await context.set_state(None)
    await event.answer(notification="")

    text = await build_main_menu_text(bot_user)
    await bot_reply(
        event,
        text=text,
        attachments=[main_menu_kb()],
        user_id=bot_user["max_user_id"],
        chat_id=event.message.recipient.chat_id if event.message else None,
    )
