from maxapi.types.attachments.attachment import Attachment
from maxapi.types.attachments.buttons import (
    CallbackButton,
    RequestContactButton,
)
from maxapi.utils.inline_keyboard import InlineKeyboardBuilder


def main_menu_kb() -> Attachment:
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="📝 Создать заявку", payload="create_ticket"))
        .row(CallbackButton(text="📋 Мои заявки", payload="view_tickets"))
        .as_markup()
    )


def contact_request_kb() -> Attachment:
    return (
        InlineKeyboardBuilder()
        .row(RequestContactButton(text="📱 Поделиться контактом"))
        .as_markup()
    )


def confirm_ticket_kb() -> Attachment:
    """Клавиатура подтверждения создания заявки."""
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="✅ Подтвердить", payload="confirm_ticket"))
        .row(CallbackButton(text="✏️ Продолжить редактирование", payload="edit_ticket"))
        .row(CallbackButton(text="❌ Отменить создание", payload="cancel_ticket"))
        .as_markup()
    )


def menu_only_kb() -> Attachment:
    """Клавиатура с единственной кнопкой возврата в главное меню."""
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
        .as_markup()
    )


def done_ticket_kb() -> Attachment:
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="✅ Готово", payload="done_ticket"))
        .row(CallbackButton(text="❌ Отменить создание", payload="cancel_ticket"))
        .as_markup()
    )


def tickets_list_kb(
    tickets: list[dict], page: int, total: int, page_size: int = 8
) -> Attachment:
    builder = InlineKeyboardBuilder()
    for t in tickets:
        desc_preview = (t["description"] or "")[:35]
        if len(t["description"] or "") > 35:
            desc_preview += "…"
        status_icon = {"open": "🔴", "in_progress": "🟡", "closed": "🟢"}.get(
            t["status"], "⚪"
        )
        builder.row(
            CallbackButton(
                text=f"#{t['id']} {status_icon} {desc_preview}",
                payload=f"ticket_detail:{t['id']}",
            )
        )

    nav = []
    if page > 0:
        nav.append(CallbackButton(text="← Назад", payload=f"tickets_page:{page - 1}"))
    if (page + 1) * page_size < total:
        nav.append(CallbackButton(text="Вперёд →", payload=f"tickets_page:{page + 1}"))
    if nav:
        builder.row(*nav)

    builder.row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
    return builder.as_markup()


def intradesk_tasks_list_kb(
    tasks: list[dict], page: int, total: int, page_size: int = 8
) -> Attachment:
    builder = InlineKeyboardBuilder()
    for t in tasks:
        name_preview = (t.get("name") or "")[:35]
        if len(t.get("name") or "") > 35:
            name_preview += "…"
        sn = (t.get("status_name") or "").lower()
        if "выполнен" in sn:
            icon = "🟢"
        elif "работ" in sn:
            icon = "🟡"
        elif "открыт" in sn:
            icon = "🔴"
        else:
            icon = "⚪"
        label = t.get("task_number") or t["id"]
        builder.row(
            CallbackButton(
                text=f"#{label} {icon} {name_preview}",
                payload=f"iticket_detail:{t['id']}",
            )
        )

    nav = []
    if page > 0:
        nav.append(CallbackButton(text="← Пред.", payload=f"itickets_page:{page - 1}"))
    if (page + 1) * page_size < total:
        nav.append(CallbackButton(text="След. →", payload=f"itickets_page:{page + 1}"))
    if nav:
        builder.row(*nav)

    builder.row(CallbackButton(text="← Назад в меню", payload="main_menu"))
    return builder.as_markup()


def iticket_detail_kb(task_id: int | None = None, can_close: bool = False) -> Attachment:
    """Клавиатура внутри карточки Intradesk-задачи."""
    builder = InlineKeyboardBuilder()
    if task_id is not None:
        builder.row(CallbackButton(
            text="💬 Оставить комментарий",
            payload=f"iticket_comment:{task_id}",
        ))
    if task_id is not None and can_close:
        builder.row(CallbackButton(
            text="🔒 Закрыть заявку",
            payload=f"iticket_close:{task_id}",
        ))
    builder.row(CallbackButton(text="← К списку заявок", payload="itickets_page:0"))
    builder.row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
    return builder.as_markup()


def comment_input_kb(task_id: int) -> Attachment:
    """Клавиатура при вводе комментария — кнопка назад и меню."""
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="← Назад к заявке", payload=f"iticket_detail:{task_id}"))
        .row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
        .as_markup()
    )


def notification_kb() -> Attachment:
    """Клавиатура под уведомлением о новом комментарии."""
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="📋 Мои заявки", payload="view_tickets"))
        .row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
        .as_markup()
    )


def ticket_detail_kb(page: int = 0) -> Attachment:
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="← К списку", payload=f"tickets_page:{page}"))
        .row(CallbackButton(text="🏠 Главное меню", payload="main_menu"))
        .as_markup()
    )
