from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup

MAIN_COACH_KB = ReplyKeyboardMarkup(
    [["➕ افزودن ورزشکار", "📋 لیست ورزشکاران"],
     ["🔎 جستجوی ورزشکار"],
     ["🏋️ تمرین پیش‌فرض", "🥗 رژیم پیش‌فرض"],
     ["📣 پیام به کاربران", "🛒 فروشگاه"]],
    resize_keyboard=True,
)
from telegram import ReplyKeyboardRemove
BACK_KB = ReplyKeyboardRemove()
SAVE_BACK_KB = ReplyKeyboardRemove()
SEARCH_EX_KB = ReplyKeyboardMarkup([["🔍 جستجوی حرکت"]], resize_keyboard=True)

def back_btn(cb="main_menu", label="🏠 بازگشت"):
    return InlineKeyboardButton(label, callback_data=cb)

def build_inline(rows):
    return InlineKeyboardMarkup(
        [[InlineKeyboardButton(l, callback_data=d) for l, d in row] for row in rows])

# Athletes
def athletes_kb(athletes):
    rows = [[InlineKeyboardButton(f"👤 {a['full_name']}", callback_data=f"athlete_{a['id']}")] for a in athletes]
    rows.append([back_btn()])
    return InlineKeyboardMarkup(rows)

def athlete_selected_kb(athlete_name):
    return ReplyKeyboardMarkup([[athlete_name], ["🏠 بازگشت به منوی اصلی"]], resize_keyboard=True)

def athlete_panel_kb():
    return build_inline([
        [("🏋️ برنامه تمرینی", "ath_training"), ("🥗 برنامه غذایی", "ath_diet")],
        [("💊 برنامه مکمل", "ath_supplement")],
        [("✏️ ویرایش اطلاعات", "edit"), ("🗑 حذف ورزشکار", "delete")],
        [("📸 گالری تصاویر", "ath_gallery_coach")],
        [("👁 نمایش کامل", "show"), ("📄 دریافت PDF", "get_pdf")],
        [("🏠 بازگشت", "main_menu")],
    ])

def edit_fields_kb():
    return build_inline([
        [("👤 نام", "edit_name"), ("📱 یوزرنیم", "edit_username")],
        [("🎂 سن", "edit_age"), ("📏 قد", "edit_height")],
        [("⚖️ وزن", "edit_weight"), ("📞 موبایل", "edit_phone")],
        [("📅 اشتراک", "edit_sub")],
        [("🔙 بازگشت", "back_to_athlete_panel")],
    ])

def confirm_delete_kb(athlete_id):
    return build_inline([
        [("✅ بله، حذف شود", f"confirm_delete_{athlete_id}"), ("❌ خیر", "cancel_delete")]
    ])

# Default Training
def default_training_menu_kb():
    return build_inline([
        [("📋 لیست برنامه‌های پیش‌فرض", "def_prog_list")],
        [("➕ ساخت برنامه جدید", "def_prog_create")],
        [("🏃 افزودن حرکت به کتابخانه", "def_ex_add")],
        [("🗒 لیست حرکات", "def_ex_list")],
        [("🏠 بازگشت", "main_menu")],
    ])

def paginated_exercises_kb(exercises, prefix, page=0, per_page=20, nav_cb="expg",
                           search_callback=None, back_cb="main_menu", show_content_emoji=False):
    """لیست حرکات صفحه‌بندی‌شده — حداکثر ۲۰ حرکت در هر صفحه (محدودیت تلگرام)."""
    total = len(exercises)
    pages = max(1, (total + per_page - 1) // per_page)
    page = max(0, min(page, pages - 1))
    chunk = exercises[page * per_page:(page + 1) * per_page]
    rows = []
    for i in range(0, len(chunk), 2):
        row = []
        for ex in chunk[i:i + 2]:
            label = ex['name']
            if show_content_emoji and (ex.get("photo_file_id") or ex.get("video_file_id") or ex.get("description")):
                label = f"📌 {label}"
            row.append(InlineKeyboardButton(f"🏋️ {label}", callback_data=f"{prefix}_{ex['id']}"))
        rows.append(row)
    nav = []
    if page > 0:
        nav.append(InlineKeyboardButton("⬅️ قبلی", callback_data=f"{nav_cb}_{page-1}"))
    nav.append(InlineKeyboardButton(f"📄 {page+1}/{pages}", callback_data=f"{nav_cb}_{page}"))
    if page < pages - 1:
        nav.append(InlineKeyboardButton("بعدی ➡️", callback_data=f"{nav_cb}_{page+1}"))
    rows.append(nav)
    if search_callback:
        rows.append([InlineKeyboardButton("🔍 جستجوی حرکت", callback_data=search_callback)])
    rows.append([InlineKeyboardButton("🔙 بازگشت", callback_data=back_cb)])
    return InlineKeyboardMarkup(rows)


def exercises_list_kb(exercises, prefix="sel_ex", search_callback="search_exercise", show_back=True, back_cb="main_menu"):
    """نمایش حرکات در ۲ ستون (دکمه جستجو به صورت دکمه کیبردی جداگانه ارسال می‌شود)."""
    rows = []
    for i in range(0, len(exercises), 2):
        row = []
        for ex in exercises[i:i+2]:
            row.append(InlineKeyboardButton(ex['name'], callback_data=f"{prefix}_{ex['id']}"))
        rows.append(row)
    if show_back:
        rows.append([back_btn(back_cb)])
    return InlineKeyboardMarkup(rows)


def exercises_library_kb(exercises, prefix="view_ex", show_back=True, back_cb="main_menu"):
    """نمایش حرکات کتابخانه برای مربی - با ایموجی کنار حرکاتی که محتوا (عکس/فیلم/توضیح) دارند."""
    rows = []
    for i in range(0, len(exercises), 2):
        row = []
        for ex in exercises[i:i+2]:
            has_content = bool(ex.get("photo_file_id") or ex.get("video_file_id") or ex.get("description"))
            label = f"📌 {ex['name']}" if has_content else ex['name']
            row.append(InlineKeyboardButton(label, callback_data=f"{prefix}_{ex['id']}"))
        rows.append(row)
    if show_back:
        rows.append([back_btn(back_cb, "🔙 بازگشت")])
    return InlineKeyboardMarkup(rows)

def default_programs_kb(programs, prefix="def_prog"):
    rows = [[InlineKeyboardButton(f"📋 {p['name']}", callback_data=f"{prefix}_{p['id']}")] for p in programs]
    rows.append([back_btn()])
    return InlineKeyboardMarkup(rows)

def program_detail_kb(program_id):
    return build_inline([
        [("🗑 حذف برنامه", f"del_def_prog_{program_id}")],
        [("🔙 بازگشت", "def_prog_list")],
    ])

def save_or_add_kb():
    return build_inline([
        [("✅ ذخیره برنامه", "prog_save"), ("➕ افزودن حرکت دیگر", "prog_add_more")],
        [("🔗 سوپر با حرکت بعدی", "prog_superset")],
    ])

# Default Diets
def default_diet_menu_kb():
    return build_inline([
        [("📋 لیست رژیم‌ها", "def_diet_list")],
        [("➕ افزودن رژیم جدید", "def_diet_add")],
        [("🏠 بازگشت", "main_menu")],
    ])

def default_diets_kb(diets, prefix="def_diet"):
    rows = [[InlineKeyboardButton(f"🥗 {d['name']}", callback_data=f"{prefix}_{d['id']}")] for d in diets]
    rows.append([back_btn()])
    return InlineKeyboardMarkup(rows)

def diet_detail_kb(diet_id):
    return build_inline([
        [("🗑 حذف رژیم", f"del_def_diet_{diet_id}")],
        [("🔙 بازگشت", "def_diet_list")],
    ])

# Athlete Training
def athlete_training_menu_kb():
    return build_inline([
        [("➕ افزودن تمرین", "ath_add_train")],
        [("✍️ دست‌نویس (هوش مصنوعی)", "ath_handwritten")],
        [("🗑 حذف تمرین", "ath_del_train")],
        [("🔙 بازگشت", "back_to_athlete_panel")],
    ])

def new_or_default_kb():
    return build_inline([
        [("🆕 جدید", "ath_train_new"), ("📋 پیش‌فرض", "ath_train_from_default")],
        [("🔙 بازگشت", "ath_training")],
    ])

def athlete_days_kb(days, athlete_id):
    rows = [[InlineKeyboardButton(f"📅 روز {d}", callback_data=f"del_ath_day_{athlete_id}_{d}")] for d in days]
    rows.append([back_btn("ath_training", "🔙 بازگشت")])
    return InlineKeyboardMarkup(rows)

# Athlete Diet
def athlete_diet_menu_kb():
    return build_inline([
        [("✏️ رژیم جدید", "ath_diet_new")],
        [("📋 رژیم پیش‌فرض", "ath_diet_from_default")],
        [("🔙 بازگشت", "back_to_athlete_panel")],
    ])

def training_days_kb(days):
    """منوی شیشه‌ای روزهای تمرین برای پنل ورزشکار."""
    rows = [[InlineKeyboardButton(f"📅 روز {d}", callback_data=f"ath_view_day_{d}")] for d in days]
    rows.append([InlineKeyboardButton("🔙 بازگشت", callback_data="ath_back_panel")])
    return InlineKeyboardMarkup(rows)


def day_exercises_kb(exercises, day_num):
    """لیست حرکات یک روز برای پنل ورزشکار - هر دکمه نمایش محتوا می‌دهد."""
    rows = []
    for ex in exercises:
        mark = "🔗 " if ex.get("superset") else ""
        if int(ex.get("sets") or 0) == 0:
            label = f"{mark}🏃 {ex['exercise_name']}  (⏱ {ex['reps']} دقیقه)"
        else:
            label = f"{mark}💪 {ex['exercise_name']}  ({ex['sets']} ست × {ex['reps']} تکرار)"
        rows.append([InlineKeyboardButton(label, callback_data=f"ath_ex_detail_{ex['exercise_id']}")])
    rows.append([InlineKeyboardButton("🔙 بازگشت به روزها", callback_data="ath_view_training")])
    return InlineKeyboardMarkup(rows)


def skip_back_kb(skip_data="skip_step"):
    return InlineKeyboardMarkup([[
        InlineKeyboardButton("🔙 بازگشت", callback_data="main_menu"),
        InlineKeyboardButton("⏭ رد کردن", callback_data=skip_data),
    ]])

# Shop
def shop_bands_with_back_kb(bands):
    rows = [[InlineKeyboardButton(f"🏷 {b['name']}", callback_data=f"shop_band_{b['id']}")] for b in bands]
    rows.append([InlineKeyboardButton("➕ افزودن دستبند", callback_data="shop_add_band")])
    rows.append([InlineKeyboardButton("🏠 بازگشت", callback_data="main_menu")])
    return InlineKeyboardMarkup(rows)

def ath_shop_bands_kb(bands):
    rows = [[InlineKeyboardButton(f"🏷 {b['name']}", callback_data=f"ath_shop_band_{b['id']}")] for b in bands]
    rows.append([InlineKeyboardButton("🔙 بازگشت", callback_data="ath_back_panel")])
    return InlineKeyboardMarkup(rows)
