"""Start command and main menu handler."""

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

from config import settings
from database import get_user_by_telegram_id, get_user_rank, get_prediction_count_for_user, get_referral_count_for_user
from keyboards.user import (
    get_start_keyboard,
    get_main_menu_keyboard,
    get_channel_keyboard,
)
from states.registration import RegistrationState
from states.admin import AdminState


router = Router()


async def is_user_member(bot, user_id: int, channel: str) -> bool:
    """Check if user is member of the mandatory channel."""
    try:
        member = await bot.get_chat_member(f"@{channel}", user_id)
        return member.status in ["member", "administrator", "creator"]
    except Exception:
        return False


@router.message(CommandStart())
async def cmd_start(message: Message, state: FSMContext):
    """Handle /start command - welcome and registration flow."""
    user = await get_user_by_telegram_id(message.from_user.id)

    if user:
        # User already registered, show main menu
        await state.clear()
        await show_main_menu(message, user)
    else:
        # New user, start registration
        await state.clear()
        referral_code = None

        # Check for referral code in start parameter
        if message.text and len(message.text.split()) > 1:
            start_param = message.text.split()[1]
            if start_param.startswith("start="):
                referral_code = start_param.split("=")[1]
            else:
                referral_code = start_param

        await state.update_data(referral_code=referral_code)
        await state.set_state(RegistrationState.waiting_for_channel_join)

        welcome_text = """
🏆 به جام جهانی ۲۰۲۶ با آکادمی گیسو خوش آمدید

اینجا می‌توانید:

⚽ مسابقات را پیش‌بینی کنید
💎 امتیاز جمع کنید
📈 در جدول رتبه‌بندی رقابت کنید
🎁 جوایز دریافت کنید
"""

        await message.answer(welcome_text, reply_markup=get_start_keyboard())


async def show_main_menu(message: Message, user: dict):
    """Show main menu for registered user."""
    score = user.get("score", 0)

    rank = await get_user_rank(user["id"])
    prediction_count = await get_prediction_count_for_user(user["id"])
    referral_count = await get_referral_count_for_user(user["id"])

    welcome_text = f"""
🏆 خوش آمدید {user.get('full_name', '')}

💎 امتیاز شما: {score}
📈 رتبه شما: {rank}
⚽ تعداد پیش بینی ها: {prediction_count}
👥 تعداد دعوت های موفق: {referral_count}
"""

    await message.answer(welcome_text, reply_markup=get_main_menu_keyboard())


@router.callback_query(F.data == "start_registration")
async def start_registration(callback: CallbackQuery, state: FSMContext):
    """Start the registration process after clicking start button."""
    await state.set_state(RegistrationState.waiting_for_channel_join)

    await callback.message.edit_text(
        "❌ برای شرکت در مسابقه ابتدا در کانال عضو شوید.",
        reply_markup=get_channel_keyboard()
    )
    await callback.answer()


@router.callback_query(F.data == "check_channel_membership")
async def check_channel_membership(callback: CallbackQuery, state: FSMContext):
    """Check if user has joined the mandatory channel."""
    from aiogram import Bot

    bot = callback.bot
    is_member = await is_user_member(bot, callback.from_user.id, settings.MANDATORY_CHANNEL)

    if is_member:
        await state.set_state(RegistrationState.waiting_for_full_name)
        await callback.message.edit_text(
            "✅ عضویت شما تایید شد!\n\nنام و نام خانوادگی خود را وارد کنید:",
            reply_markup=None
        )
    else:
        await callback.answer("❌ هنوز عضو کانال نیستید. لطفاً ابتدا عضو کانال شوید.", show_alert=True)


@router.callback_query(F.data == "back_to_menu")
async def back_to_menu(callback: CallbackQuery, state: FSMContext):
    """Return to main menu from any section."""
    await state.clear()

    from database import get_user_by_telegram_id
    user = await get_user_by_telegram_id(callback.from_user.id)

    if user:
        await show_main_menu(callback.message, user)
    else:
        await callback.message.edit_text(
            "🏆 به جام جهانی ۲۰۲۶ با آکادمی گیسو خوش آمدید",
            reply_markup=get_start_keyboard()
        )