"""Admin panel home, cancellation and reply-keyboard shortcuts."""

from __future__ import annotations

import logging

from aiogram import F, Router
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message, ReplyKeyboardMarkup

from app.context import AppContext
from app.handlers.common import show_home

logger = logging.getLogger(__name__)
router = Router(name="admin_menu")

PANEL_KEYBOARD = ReplyKeyboardMarkup(
    keyboard=[
        [{"text": "🎛 پنل مدیریت"}, {"text": "📊 آمار"}],
        [{"text": "❌ لغو"}],
    ],
    resize_keyboard=True,
    input_field_placeholder="از منوی مدیریت استفاده کنید",
)


async def _guard_private(message: Message) -> bool:
    if message.chat.type != "private":
        await message.answer("پنل مدیریت فقط در گفت‌وگوی خصوصی ربات در دسترس است.")
        return False
    return True


@router.message(Command("admin"))
async def admin_command(message: Message, ctx: AppContext) -> None:
    if not await _guard_private(message):
        return
    await show_home(message, ctx)
    await message.answer("میانبرهای پنل فعال شد.", reply_markup=PANEL_KEYBOARD)


@router.message(F.text == "🎛 پنل مدیریت")
async def panel_button(message: Message, ctx: AppContext) -> None:
    if await _guard_private(message):
        await show_home(message, ctx)


@router.message(F.text == "📊 آمار")
async def stats_button(message: Message, ctx: AppContext) -> None:
    if not await _guard_private(message):
        return
    from app.handlers.statistics import render_dashboard

    await render_dashboard(message, ctx)


@router.message(F.text == "❌ لغو")
async def cancel_button(message: Message, state: FSMContext, ctx: AppContext) -> None:
    await state.clear()
    await message.answer("عملیات جاری لغو شد.", reply_markup=PANEL_KEYBOARD)
    await show_home(message, ctx)


@router.callback_query(F.data == "menu:home")
async def home(callback: CallbackQuery, ctx: AppContext) -> None:
    await show_home(callback, ctx)
    await callback.answer()


@router.callback_query(F.data == "noop")
async def noop(callback: CallbackQuery) -> None:
    await callback.answer()


@router.callback_query(F.data == "flow:cancel")
async def cancel_flow(callback: CallbackQuery, state: FSMContext, ctx: AppContext) -> None:
    await state.clear()
    await show_home(callback, ctx)
    await callback.answer("لغو شد.")
