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 done_ticket_kb() -> Attachment:
    return (
        InlineKeyboardBuilder()
        .row(CallbackButton(text="✅ Готово", payload="done_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 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()
    )
