from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup

from app.schedule_utils import (
    RUN_MODE_SCHEDULE,
    WEEKDAY_LABELS,
    normalize_work_days,
)


def start_kb():
    """Главное меню: управление + входы в подменю."""
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(text="▶️ Запуск", callback_data="startparsing"),
                InlineKeyboardButton(text="⏹ Стоп", callback_data="stopparsing"),
            ],
            [InlineKeyboardButton(text="📊 Статус", callback_data="bot_status")],
            [InlineKeyboardButton(text="📋 Мои задачи", callback_data="mytask")],
            [InlineKeyboardButton(text="⚙️ Настройки", callback_data="settings_hub")],
            [InlineKeyboardButton(text="📈 Статистика", callback_data="stats_hub")],
        ]
    )


def settings_hub_kb():
    """Подменю настроек."""
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(
                    text="🔎 Фильтр объявлений",
                    callback_data="settings_filter",
                )
            ],
            [
                InlineKeyboardButton(
                    text="⏰ Расписание работы",
                    callback_data="settings_schedule",
                )
            ],
            [
                InlineKeyboardButton(
                    text="💬 SMS",
                    callback_data="sms_settings",
                )
            ],
            [
                InlineKeyboardButton(
                    text="🧪 Debug-парсинг",
                    callback_data="debugparsing",
                )
            ],
            [
                InlineKeyboardButton(
                    text="📘 Общие параметры",
                    callback_data="settings_general",
                )
            ],
            [InlineKeyboardButton(text="⬅️ В меню", callback_data="backstart")],
        ]
    )


def stats_hub_kb():
    """Подменю статистики."""
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(
                    text="🚗 Статистика парсинга",
                    callback_data="statistic",
                )
            ],
            [
                InlineKeyboardButton(
                    text="💬 Статистика SMS",
                    callback_data="staticsms",
                )
            ],
            [
                InlineKeyboardButton(
                    text="⏳ Очередь SMS",
                    callback_data="pending_sms_queue",
                )
            ],
            [
                InlineKeyboardButton(
                    text="📑 Дневной отчёт сейчас",
                    callback_data="daily_report_now",
                )
            ],
            [InlineKeyboardButton(text="⬅️ В меню", callback_data="backstart")],
        ]
    )


def settings_kb():
    """Фильтр объявлений."""
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text="Тип автомобиля", callback_data="typeAuto")],
            [
                InlineKeyboardButton(text="Регион", callback_data="regionsettings"),
                InlineKeyboardButton(text="Год", callback_data="yearsettings"),
            ],
            [InlineKeyboardButton(text="Цена", callback_data="pricesettings")],
            [InlineKeyboardButton(text="♻️ Сброс фильтров", callback_data="reset_filters")],
            [InlineKeyboardButton(text="⬅️ К настройкам", callback_data="settings_hub")],
        ]
    )


def schedule_kb(run_mode: str | None = None) -> InlineKeyboardMarkup:
    is_schedule = (run_mode or "") == RUN_MODE_SCHEDULE
    mode_btn = (
        "🔁 Режим: По расписанию ✅"
        if is_schedule
        else "🔁 Режим: Вручную"
    )
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text=mode_btn, callback_data="schedule_toggle_mode")],
            [
                InlineKeyboardButton(text="🕒 Время «с»", callback_data="schedule_set_from"),
                InlineKeyboardButton(text="🕔 Время «до»", callback_data="schedule_set_to"),
            ],
            [InlineKeyboardButton(text="📅 Дни недели", callback_data="schedule_days")],
            [InlineKeyboardButton(text="⬅️ К настройкам", callback_data="settings_hub")],
        ]
    )


def schedule_days_kb(selected_days) -> InlineKeyboardMarkup:
    selected = set(normalize_work_days(selected_days))
    rows = []
    row = []
    for day in range(7):
        mark = "✅ " if day in selected else ""
        row.append(
            InlineKeyboardButton(
                text=f"{mark}{WEEKDAY_LABELS[day]}",
                callback_data=f"toggle_weekday_{day}",
            )
        )
        if len(row) == 4 or day == 6:
            rows.append(row)
            row = []
    rows.append(
        [
            InlineKeyboardButton(text="Пн–Пт", callback_data="schedule_days_weekdays"),
            InlineKeyboardButton(text="Все дни", callback_data="schedule_days_all"),
        ]
    )
    rows.append(
        [InlineKeyboardButton(text="⬅️ Назад к расписанию", callback_data="settings_schedule")]
    )
    return InlineKeyboardMarkup(inline_keyboard=rows)


def sms_settings_kb():
    """Настройки SMS (вход из «Настройки»)."""
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text="✏️ Изменить текст", callback_data="change_sms_text")],
            [
                InlineKeyboardButton(
                    text="📝 Изменить отправителя",
                    callback_data="change_sms_sender",
                )
            ],
            [
                InlineKeyboardButton(
                    text="👀 Просмотр настроек",
                    callback_data="view_sms_settings",
                )
            ],
            [
                InlineKeyboardButton(
                    text="⏳ Очередь SMS",
                    callback_data="pending_sms_queue",
                )
            ],
            [
                InlineKeyboardButton(
                    text="📤 Тест SMS",
                    callback_data="test_sms",
                )
            ],
            [InlineKeyboardButton(text="⬅️ К настройкам", callback_data="settings_hub")],
        ]
    )


def pending_sms_queue_kb(*, has_items: bool) -> InlineKeyboardMarkup:
    rows = []
    if has_items:
        rows.append(
            [
                InlineKeyboardButton(
                    text="🚀 Отправить всю очередь сейчас",
                    callback_data="pending_sms_flush_ask",
                )
            ]
        )
    rows.append(
        [InlineKeyboardButton(text="🔄 Обновить", callback_data="pending_sms_queue")]
    )
    rows.append(
        [InlineKeyboardButton(text="⬅️ Назад", callback_data="stats_hub")]
    )
    return InlineKeyboardMarkup(inline_keyboard=rows)


def pending_sms_flush_confirm_kb() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(
                    text="✅ Да, отправить всё",
                    callback_data="pending_sms_flush_now",
                )
            ],
            [
                InlineKeyboardButton(
                    text="⬅️ Отмена",
                    callback_data="pending_sms_queue",
                )
            ],
        ]
    )
