"""User registration handlers."""

import random
import string
from aiogram import Router, F
from aiogram.types import Message, CallbackQuery, ReplyKeyboardRemove
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
from aiogram.fsm.context import FSMContext

from states.registration import RegistrationState
from keyboards.user import get_role_keyboard, get_main_menu_keyboard
from database import (
    create_user,
    get_user_by_referral_code,
    get_user_by_telegram_id
)
from services.referrals import process_referral


router = Router()


@router.message(RegistrationState.waiting_for_full_name)
async def process_full_name(message: Message, state: FSMContext):
    """Receive full name and ask for phone number."""
    if not message.text or len(message.text.strip()) < 2:
        await message.answer("❌ نام و نام خانوادگی را باید به طور کامل وارد کنید.")
        return

    full_name = message.text.strip()
    await state.update_data(full_name=full_name)
    await state.set_state(RegistrationState.waiting_for_phone)

    contact_keyboard = ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text="📱 اشتراک گذاری شماره تماس", request_contact=True)]],
        resize_keyboard=True
    )

    await message.answer(
        "📱 لطفاً شماره تماس خود را با فشار دادن دکمه زیر ارسال کنید.",
        reply_markup=contact_keyboard
    )


@router.message(RegistrationState.waiting_for_phone, F.contact)
async def process_phone(message: Message, state: FSMContext):
    """Receive valid phone number via contact sharing."""
    phone = message.contact.phone_number
    await state.update_data(phone=phone)
    await state.set_state(RegistrationState.waiting_for_role)

    await message.answer(
        "✅ شماره شما ثبت شد.",
        reply_markup=ReplyKeyboardRemove()
    )

    await message.answer(
        "🔹 نقش خود را انتخاب کنید:",
        reply_markup=get_role_keyboard()
    )


@router.message(RegistrationState.waiting_for_phone)
async def process_phone_invalid(message: Message):
    """Handle when user sends text instead of contact."""
    await message.answer(
        "❌ لطفاً برای ثبت شماره تماس، دکمه «اشتراک گذاری شماره تماس» را فشار دهید."
    )


@router.callback_query(
    RegistrationState.waiting_for_role,
    F.data.in_({"role_dentist", "role_student"})
)
async def process_role(callback: CallbackQuery, state: FSMContext):
    """Process role selection, create user and show main menu."""
    role = "دندانپزشک" if callback.data == "role_dentist" else "دانشجو"

    data = await state.get_data()
    full_name = data.get("full_name")
    phone = data.get("phone")
    referral_code_input = data.get("referral_code")  

    referral_code = "".join(random.choices(string.ascii_uppercase + string.digits, k=8))

    inviter_id = None
    if referral_code_input:
        inviter = await get_user_by_referral_code(referral_code_input)
        if inviter:
            inviter_id = inviter["id"]

    user_id = await create_user(
        telegram_id=callback.from_user.id,
        full_name=full_name,
        phone=phone,
        role=role,
        referral_code=referral_code,
        invited_by=inviter_id
    )

    if inviter_id:
        await process_referral(callback.from_user.id, referral_code_input)

    await state.clear()

    try:
        await callback.message.delete()
    except Exception:
        pass

    await callback.message.answer(
        f"✅ ثبت نام شما با موفقیت انجام شد!\n\n"
        f"🏆 خوش آمدید {full_name}\n"
        f"🔑 کد معرف شما: `{referral_code}`",
        reply_markup=get_main_menu_keyboard(),
        parse_mode="Markdown"
    )
    await callback.answer()


@router.callback_query(F.data == "back_to_menu", RegistrationState.waiting_for_role)
async def back_to_menu_from_role(callback: CallbackQuery, state: FSMContext):
    """Cancel registration and go back to main menu (if user already exists)."""
    user = await get_user_by_telegram_id(callback.from_user.id)
    if user:
        from handlers.start import show_main_menu
        await show_main_menu(callback.message, user)
    else:
        await callback.message.answer("❌ خطا: لطفاً مجدداً شروع کنید /start")
    await callback.answer()