"""
Broadcast + Direct messaging athlete ↔ coach.
"""
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import (
    ContextTypes, ConversationHandler,
    MessageHandler, CallbackQueryHandler, filters,
)
import database.db as db
from config.settings import COACHES, BROADCAST_TEXT, ATH_MSG_TO_COACH, COACH_REPLY_STATE
from utils.keyboards import MAIN_COACH_KB, BACK_KB
from utils.helpers import go_main_menu, track_message, delete_bot_messages
import config.settings as _cfg


async def _cancel(update, context):
    await go_main_menu(update, context)
    return ConversationHandler.END


# ══ BROADCAST ═════════════════════════════════════════════════════════════════

async def broadcast_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    chat_id = update.effective_chat.id
    await delete_bot_messages(context, chat_id)
    sent = await update.message.reply_text(
        "📣 *پیام به همه ورزشکاران*\n\n"
        "متن پیام را بنویس — به همه کسانی که ربات را استارت زده‌اند ارسال می‌شود:",
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="main_menu")]]), parse_mode="Markdown")
    track_message(context, chat_id, sent.message_id)
    return BROADCAST_TEXT


async def broadcast_got_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = update.message.text.strip()
    athletes = db.get_all_athletes()
    chat_id = update.effective_chat.id
    ok, fail = 0, 0

    status = await update.message.reply_text(f"⏳ ارسال به {len(athletes)} نفر...")
    track_message(context, chat_id, status.message_id)

    for a in athletes:
        full = db.get_athlete(a['id'])
        tg_id = full.get('telegram_id')
        if not tg_id:
            fail += 1; continue
        try:
            await context.bot.send_message(
                chat_id=tg_id,
                text=f"📣 *پیام از مربی:*\n\n{text}",
                parse_mode="Markdown")
            ok += 1
        except Exception:
            fail += 1

    await delete_bot_messages(context, chat_id)
    sent = await update.message.reply_text(
        f"✅ ارسال تمام شد!\n\n📬 موفق: {ok} نفر\n❌ ناموفق: {fail} نفر",
        reply_markup=MAIN_COACH_KB)
    track_message(context, chat_id, sent.message_id)
    return ConversationHandler.END


# ══ ATHLETE → COACH ═══════════════════════════════════════════════════════════

async def ath_contact_coach_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query; await query.answer()
    chat_id = query.message.chat_id
    await delete_bot_messages(context, chat_id)
    kb = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="ath_back_panel")]])
    sent = await query.message.reply_text(
        "💬 *ارتباط با مربی*\n\nپیام خود را بنویسید:",
        reply_markup=kb, parse_mode="Markdown")
    track_message(context, chat_id, sent.message_id)
    return ATH_MSG_TO_COACH


async def ath_msg_send(update: Update, context: ContextTypes.DEFAULT_TYPE):
    athlete_id  = context.user_data.get("athlete_user_id")
    athlete     = db.get_athlete(athlete_id) if athlete_id else None
    name        = athlete["full_name"] if athlete else "ناشناس"
    username    = (athlete.get("username") or "") if athlete else ""
    phone       = (athlete.get("phone") or "")    if athlete else ""
    sender_chat = update.effective_chat.id
    msg_text    = update.message.text.strip()

    # Persist athlete telegram_id
    if athlete_id:
        db.save_athlete_chat_id(athlete_id, sender_chat)

    # Encode chat_id safely: replace "-" with "n" prefix for negative IDs
    encoded = str(sender_chat).replace("-", "n")

    coach_text = (
        f"💬 *پیام جدید از ورزشکار*\n\n"
        f"👤 {name}"
        + (f" (@{username})" if username else "") + "\n"
        + (f"📞 {phone}\n" if phone else "")
        + f"\n📝 {msg_text}"
    )
    reply_kb = InlineKeyboardMarkup([[
        InlineKeyboardButton(
            f"↩️ پاسخ به {name}",
            callback_data=f"replyto_{athlete_id or 0}_{encoded}"
        )
    ]])
    # Send to coach (try COACH_CHAT_ID first, then try all coaches by username)
    sent_ok = False
    if _cfg.COACH_CHAT_ID:
        try:
            await context.bot.send_message(
                chat_id=_cfg.COACH_CHAT_ID,
                text=coach_text,
                reply_markup=reply_kb,
                parse_mode="Markdown")
            sent_ok = True
        except Exception:
            pass
    if not sent_ok:
        # Try sending via username
        from config.settings import COACHES
        for coach_username in COACHES:
            try:
                await context.bot.send_message(
                    chat_id=f"@{coach_username}",
                    text=coach_text,
                    reply_markup=reply_kb,
                    parse_mode="Markdown")
                sent_ok = True
                break
            except Exception:
                pass

    chat_id = update.effective_chat.id
    await delete_bot_messages(context, chat_id)
    kb = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="ath_back_panel")]])
    sent = await update.message.reply_text(
        "✅ پیام شما به مربی ارسال شد!\nبه زودی پاسخ می‌گیرید 🙏",
        reply_markup=kb)
    track_message(context, chat_id, sent.message_id)
    return ConversationHandler.END


# ══ COACH → ATHLETE ═══════════════════════════════════════════════════════════

async def coach_reply_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query; await query.answer()
    # format: replyto_{athlete_id}_{encoded_chat_id}
    parts = query.data.split("_")           # ['replyto', '123', 'n1001234567890'] or ['replyto','123','1234567890']
    athlete_id_str = parts[1]
    encoded_chat   = parts[2]

    # Decode chat_id
    if encoded_chat.startswith("n"):
        target_chat = int("-" + encoded_chat[1:])
    else:
        target_chat = int(encoded_chat)

    athlete_id = int(athlete_id_str) if athlete_id_str.isdigit() else 0
    context.user_data["reply_target_chat"]    = target_chat
    context.user_data["reply_target_athlete"] = athlete_id

    athlete = db.get_athlete(athlete_id) if athlete_id else None
    name    = athlete["full_name"] if athlete else "ورزشکار"

    # Don't delete all messages — coach needs context; just send new prompt
    kb = InlineKeyboardMarkup([[InlineKeyboardButton("❌ لغو", callback_data="main_menu")]])
    sent = await query.message.reply_text(
        f"↩️ *پاسخ به {name}*\n\nپیام خود را بنویسید:",
        reply_markup=kb, parse_mode="Markdown")
    track_message(context, query.message.chat_id, sent.message_id)
    return COACH_REPLY_STATE


async def coach_reply_send(update: Update, context: ContextTypes.DEFAULT_TYPE):
    reply_text  = update.message.text.strip()
    target_chat = context.user_data.get("reply_target_chat")
    athlete_id  = context.user_data.get("reply_target_athlete")
    athlete     = db.get_athlete(athlete_id) if athlete_id else None
    name        = athlete["full_name"] if athlete else "ورزشکار"
    chat_id     = update.effective_chat.id

    if target_chat:
        try:
            ath_kb = InlineKeyboardMarkup([[
                InlineKeyboardButton("💬 پاسخ به مربی", callback_data="ath_contact_coach")
            ]])
            await context.bot.send_message(
                chat_id=target_chat,
                text=f"📩 *پاسخ از مربی:*\n\n{reply_text}",
                reply_markup=ath_kb,
                parse_mode="Markdown")
            await delete_bot_messages(context, chat_id)
            sent = await update.message.reply_text(
                f"✅ پاسخ به *{name}* ارسال شد! ✉️",
                reply_markup=MAIN_COACH_KB, parse_mode="Markdown")
            track_message(context, chat_id, sent.message_id)
        except Exception as e:
            sent = await update.message.reply_text(
                f"❌ خطا در ارسال:\n{e}", reply_markup=MAIN_COACH_KB)
            track_message(context, chat_id, sent.message_id)
    return ConversationHandler.END


# ── Conversations ──────────────────────────────────────────────────────────────

broadcast_conv = ConversationHandler(
    entry_points=[MessageHandler(filters.Regex("^📣 پیام به کاربران$"), broadcast_start)],
    states={BROADCAST_TEXT: [MessageHandler(filters.TEXT & ~filters.COMMAND, broadcast_got_text)]},
    fallbacks=[CallbackQueryHandler(_cancel, pattern="^main_menu$")],
    per_message=False,
)

ath_contact_conv = ConversationHandler(
    entry_points=[CallbackQueryHandler(ath_contact_coach_start, pattern="^ath_contact_coach$")],
    states={ATH_MSG_TO_COACH: [MessageHandler(filters.TEXT & ~filters.COMMAND, ath_msg_send)]},
    fallbacks=[CallbackQueryHandler(_cancel, pattern="^main_menu$"),
               CallbackQueryHandler(_cancel, pattern="^ath_back_panel$")],
    per_message=False,
)

coach_reply_conv = ConversationHandler(
    entry_points=[CallbackQueryHandler(coach_reply_start, pattern=r"^replyto_\d+_.+$")],
    states={COACH_REPLY_STATE: [MessageHandler(filters.TEXT & ~filters.COMMAND, coach_reply_send)]},
    fallbacks=[CallbackQueryHandler(_cancel, pattern="^main_menu$")],
    per_message=False,
)


def register(app):
    app.add_handler(broadcast_conv)
    app.add_handler(ath_contact_conv)
    app.add_handler(coach_reply_conv)
