from aiogram.types import CallbackQuery, Message, InlineKeyboardMarkup, InlineKeyboardButton

"""Prediction handlers."""

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

from states.prediction import PredictionState
from utils.helpers import gregorian_to_persian
from keyboards.user import (
    get_upcoming_matches_keyboard,
    get_prediction_type_keyboard,
    get_result_prediction_keyboard,
    get_back_to_menu_keyboard,
)
from database import (
    get_upcoming_matches,
    get_match,
    get_prediction,
    create_prediction,
    update_prediction,
    update_user_score,
)
from config import settings


router = Router()


@router.callback_query(F.data == "predict_matches")
async def show_upcoming_matches(callback: CallbackQuery, state: FSMContext):
    """Show list of upcoming matches for prediction."""
    matches = await get_upcoming_matches()

    if not matches:
        await callback.message.edit_text(
            "⚽ مسابقه‌ای در دسترس نیست.",
            reply_markup=get_back_to_menu_keyboard()
        )
        await callback.answer()
        return

    matches_text = "⚽ **مسابقات فعال**\n\n"
    for idx, match in enumerate(matches, 1):
        team1_flag = match.get("team1_flag", "")
        team2_flag = match.get("team2_flag", "")
        team1 = match.get("team1", "")
        team2 = match.get("team2", "")
        match_time = match.get("match_time", "")
        time_str = gregorian_to_persian(match_time) if match_time else ""
        
        matches_text += f"{idx}. {team1_flag} **{team1}** vs **{team2}** {team2_flag}\n"
        matches_text += f"   ⏰ {time_str}\n\n"

    await callback.message.edit_text(
        matches_text,
        reply_markup=get_upcoming_matches_keyboard(matches),
        parse_mode="Markdown"
    )
    await callback.answer()


@router.callback_query(F.data.startswith("match_"))
async def select_match_for_prediction(callback: CallbackQuery, state: FSMContext):
    """Select a match for prediction - show prediction type options."""
    match_id = int(callback.data.split("_")[1])

    match = await get_match(match_id)
    if not match:
        await callback.answer("❌ مسابقه یافت نشد.", show_alert=True)
        return

    match_time = match.get("match_time")
    if match_time and match_time <= datetime.now():
        await callback.answer("❌ این مسابقه قبلا شروع شده است.", show_alert=True)
        return

    await state.set_state(PredictionState.waiting_for_prediction_type)
    await state.update_data(match_id=match_id)

    team1_flag = match.get("team1_flag", "")
    team2_flag = match.get("team2_flag", "")
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")
    match_time = match.get("match_time")
    time_str = gregorian_to_persian(match_time) if match_time else ""

    await callback.message.edit_text(
        f"{team1_flag} {team1} vs {team2} {team2_flag}\n{time_str}\n\n"
        f"لطفاً نوع پیش‌بینی را انتخاب کنید:",
        reply_markup=get_prediction_type_keyboard(match_id)
    )
    await callback.answer()


@router.callback_query(F.data.startswith("predict_result_"))
async def predict_result_selected(callback: CallbackQuery, state: FSMContext):
    """Handle result prediction type selection (win/lose/draw)."""
    match_id = int(callback.data.split("_")[-1])

    match = await get_match(match_id)
    if not match:
        await callback.answer("❌ مسابقه یافت نشد.", show_alert=True)
        return

    team1_flag = match.get("team1_flag", "")
    team2_flag = match.get("team2_flag", "")
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")

    await state.set_state(PredictionState.waiting_for_result_prediction)
    await state.update_data(match_id=match_id)

    await callback.message.edit_text(
        f"{team1_flag} {team1}\nvs\n{team2_flag} {team2}\n\n"
        f"نتیجه پیش‌بینی را انتخاب کنید:",
        reply_markup=get_result_prediction_keyboard(team1, team2) 
    )
    await callback.answer()


@router.callback_query(F.data.startswith("predict_score_"))
async def predict_score_selected(callback: CallbackQuery, state: FSMContext):
    """Handle score prediction type selection - proceed to team1 score input."""
    match_id = int(callback.data.split("_")[-1])

    match = await get_match(match_id)
    if not match:
        await callback.answer("❌ مسابقه یافت نشد.", show_alert=True)
        return

    team1_flag = match.get("team1_flag", "")
    team2_flag = match.get("team2_flag", "")
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")

    await state.set_state(PredictionState.waiting_for_team1_score)
    await state.update_data(match_id=match_id)

    await callback.message.edit_text(
        f"{team1_flag} {team1} vs {team2} {team2_flag}\n\n"
        f"تعداد گل {team1} را وارد کنید:",
        reply_markup=get_back_to_menu_keyboard()
    )
    await callback.answer()


@router.callback_query(F.data.in_({"result_team1_win", "result_draw", "result_team2_win"}))
async def process_result_prediction(callback: CallbackQuery, state: FSMContext):
    """Process result prediction selection (team1 win / draw / team2 win)."""
    result_map = {
        "result_team1_win": "team1",
        "result_draw": "draw",
        "result_team2_win": "team2"
    }

    predict_result = result_map.get(callback.data)
    if not predict_result:
        await callback.answer("❌ خطا: نوع پیش‌بینی نامعتبر است.", show_alert=True)
        return

    data = await state.get_data()
    match_id = data.get("match_id")

    if not match_id:
        await callback.answer("❌ خطا: مسابقه مشخص نشده است. لطفاً دوباره شروع کنید.", show_alert=True)
        await state.clear()
        return

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

    if user:
        existing = await get_prediction(user["id"], match_id)
        if existing:
            await update_prediction(user["id"], match_id, predict_result=predict_result)
        else:
            await create_prediction(user["id"], match_id, predict_result=predict_result)
            await update_user_score(user["id"], settings.SCORE_PREDICTION_REGISTERED)

    match = await get_match(match_id)
    team1_flag = match.get("team1_flag", "")
    team2_flag = match.get("team2_flag", "")
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")

    # ساخت متن نمایش نتیجه با اسم تیم‌ها
    if predict_result == "team1":
        result_display = f"برد {team1}"
    elif predict_result == "draw":
        result_display = "مساوی"
    else:
        result_display = f"برد {team2}"

    await state.clear()

    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text="⚽ پیش‌بینی دقیق تعداد گل‌های هر دو تیم", callback_data=f"predict_score_{match_id}")],
            [InlineKeyboardButton(text="🔙 بازگشت به منو", callback_data="back_to_menu")]
        ]
    )

    await callback.message.edit_text(
        f"✅ پیش‌بینی نتیجه ثبت شد.\n\n"
        f"{team1_flag} {team1} vs {team2} {team2_flag}\n"
        f"پیش‌بینی شما: {result_display}\n\n"
        f"📍 همچنین می‌توانید پیش‌بینی دقیق گل را نیز ثبت کنید.",
        reply_markup=keyboard
    )
    await callback.answer()


@router.callback_query(PredictionState.waiting_for_result_prediction, F.data == "back_to_menu")
async def back_to_menu_from_result_prediction(callback: CallbackQuery, state: FSMContext):
    """Cancel result prediction and go back to menu."""
    await state.clear()
    from handlers.start import show_main_menu
    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)
    await callback.answer()


@router.callback_query(PredictionState.waiting_for_prediction_type, F.data == "back_to_menu")
async def back_to_menu_from_prediction_type(callback: CallbackQuery, state: FSMContext):
    """Cancel prediction type selection and go back to menu."""
    await state.clear()
    from handlers.start import show_main_menu
    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)
    await callback.answer()


@router.message(PredictionState.waiting_for_team1_score)
async def process_team1_score(message: Message, state: FSMContext):
    """Process team1 score input."""
    try:
        score = int(message.text)
        if score < 0:
            raise ValueError()
    except (ValueError, TypeError):
        await message.answer("❌ لطفاً عددی معتبر وارد کنید (عدد غیر منفی).")
        return

    await state.update_data(team1_score=score)
    await state.set_state(PredictionState.waiting_for_team2_score)

    data = await state.get_data()
    match = await get_match(data["match_id"])

    team1 = match.get("team1", "")
    team2 = match.get("team2", "")

    await message.answer(f"تعداد گل {team2} را وارد کنید:")


@router.message(PredictionState.waiting_for_team2_score)
async def process_team2_score(message: Message, state: FSMContext):
    """Process team2 score input and save prediction."""
    try:
        score = int(message.text)
        if score < 0:
            raise ValueError()
    except (ValueError, TypeError):
        await message.answer("❌ لطفاً عددی معتبر وارد کنید (عدد غیر منفی).")
        return

    data = await state.get_data()
    match_id = data["match_id"]
    team1_score = data["team1_score"]
    team2_score = score

    # Check if prediction already exists
    from database import get_user_by_telegram_id
    user = await get_user_by_telegram_id(message.from_user.id)

    if user:
        existing = await get_prediction(user["id"], match_id)
        if existing:
            await update_prediction(user["id"], match_id, team1_score, team2_score)
        else:
            await create_prediction(user["id"], match_id, team1_score, team2_score)
            await update_user_score(user["id"], settings.SCORE_PREDICTION_REGISTERED)

    await state.clear()

    match = await get_match(match_id)
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")

    await message.answer(
        f"✅ پیش بینی ثبت شد.\n\n{team1} {team1_score} - {team2_score} {team2}",
        reply_markup=get_back_to_menu_keyboard()
    )


@router.callback_query(PredictionState.waiting_for_team1_score, F.data == "back_to_menu")
async def back_to_menu_from_prediction(callback: CallbackQuery, state: FSMContext):
    """Cancel prediction and go back to menu."""
    await state.clear()
    from handlers.start import show_main_menu
    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)
    await callback.answer()