"""Telegram bot: user-facing handlers (catalog, cart, checkout, tickets, account)."""
import html
import json
import logging

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ChatAction, ParseMode
from telegram.ext import ContextTypes

from . import store
from .catalog import catalog_text, format_price, service_detail_text
from .orders import code_expired, expires_at
from .payments import find_order_by_any, normalize_code, valid_code_shape

log = logging.getLogger(__name__)

SESSION_CART = "cart"


def _esc(text):
    return html.escape(str(text or ""))


async def _reply(update, text, **kwargs):
    kwargs.setdefault("parse_mode", ParseMode.HTML)
    try:
        return await update.message.reply_text(text, **kwargs)
    except Exception:
        kwargs.pop("parse_mode", None)
        return await update.message.reply_text(text.replace("<", "&lt;").replace(">", "&gt;"), **kwargs)


def _cart_raw(user_id):
    return store.get_setting("cart:" + str(user_id)) or "[]"


def _cart_lines(user_id):
    try:
        return json.loads(_cart_raw(user_id))
    except Exception:
        return []


def _set_cart(user_id, cart):
    store.set_settings({"cart:" + str(user_id): json.dumps(cart)})


def _services():
    conn = store.connect()
    try:
        return conn.execute("SELECT * FROM services WHERE enabled=1 ORDER BY sort_order, id").fetchall()
    finally:
        conn.close()


def _service(code):
    conn = store.connect()
    try:
        return conn.execute("SELECT * FROM services WHERE code=?", (code,)).fetchone()
    finally:
        conn.close()


def catalog_keyboard(services):
    rows = [[InlineKeyboardButton(s["name"], callback_data=f"svc:{s['code']}")] for s in services]
    rows += [
        [InlineKeyboardButton("🛒 سبد خرید", callback_data="cart")],
        [InlineKeyboardButton("💳 پرداخت", callback_data="pay")],
        [InlineKeyboardButton("🎫 تیکت", callback_data="ticket")],
        [InlineKeyboardButton("👤 حساب من", callback_data="account")],
    ]
    return InlineKeyboardMarkup(rows)


async def cmd_start(update, context):
    user = update.effective_user
    await context.bot.send_chat_action(user.id, ChatAction.TYPING)
    await _reply(update, f"سلام {_esc(user.first_name)} 👋 به فروشگاه پنل خوش آمدید.")
    await _send_catalog(update)


async def _send_catalog(update):
    services = _services()
    await _reply(update, catalog_text(services), reply_markup=catalog_keyboard(services))


async def cmd_catalog(update, context):
    await _send_catalog(update)


async def cb_service(update, context):
    query = update.callback_query
    await query.answer()
    code = query.data.split(":", 1)[1]
    svc = _service(code)
    if not svc:
        await _reply(update, "این محصول یافت نشد.")
        return
    await _reply(update, service_detail_text(svc) + "\n\nبرای افزودن به سبد روی «➕» بزن.")


def cart_text(cart):
    if not cart:
        return "🛒 سبد خرید خالی است."
    lines = ["🛒 <b>سبد خرید</b>", ""]
    for item in cart:
        lines.append(f"• {_esc(item['name'])} × {item['qty']} = {format_price(item['line_total'])}")
    lines.append("")
    lines.append(f"<b>مجموع: {format_price(sum(i['line_total'] for i in cart))}</b>")
    return "\n".join(lines)


def cart_keyboard(cart):
    rows = []
    for item in cart:
        rows.append([
            InlineKeyboardButton(f"− {item['name']}", callback_data=f"cart_minus:{item['code']}"),
            InlineKeyboardButton(f"+ {item['name']}", callback_data=f"cart_plus:{item['code']}"),
        ])
    rows.append([InlineKeyboardButton("🗑 خالی", callback_data="cart_clear")])
    rows.append([InlineKeyboardButton("💳 پرداخت", callback_data="checkout")])
    rows.append([InlineKeyboardButton("🔙 فهرست", callback_data="catalog")])
    return InlineKeyboardMarkup(rows)


async def cb_cart(update, context):
    query = update.callback_query
    await query.answer()
    cart = _cart_lines(update.effective_user.id)
    await _reply(update, cart_text(cart), reply_markup=cart_keyboard(cart))


async def cb_cart_plus(update, context):
    query = update.callback_query
    await query.answer()
    code = query.data.split(":", 1)[1]
    svc = _service(code)
    if not svc:
        return
    user = update.effective_user
    cart = _cart_lines(user.id)
    found = False
    for item in cart:
        if item["code"] == code:
            item["qty"] += 1
            item["line_total"] = item["unit"] * item["qty"]
            found = True
            break
    if not found:
        cart.append({"code": code, "name": svc["name"], "qty": 1, "unit": svc["price_toman"],
                     "line_total": svc["price_toman"], "rebecca_service_id": svc["rebecca_service_id"]})
    _set_cart(user.id, cart)
    await _reply(update, cart_text(cart), reply_markup=cart_keyboard(cart))


async def cb_cart_minus(update, context):
    query = update.callback_query
    await query.answer()
    code = query.data.split(":", 1)[1]
    user = update.effective_user
    cart = _cart_lines(user.id)
    for item in cart:
        if item["code"] == code:
            item["qty"] -= 1
            if item["qty"] <= 0:
                cart = [c for c in cart if c["code"] != code]
            else:
                item["line_total"] = item["unit"] * item["qty"]
            break
    _set_cart(user.id, cart)
    await _reply(update, cart_text(cart), reply_markup=cart_keyboard(cart))


async def cb_cart_clear(update, context):
    query = update.callback_query
    await query.answer()
    _set_cart(update.effective_user.id, [])
    await _reply(update, "سبد خرید خالی شد.")


async def cb_ticket(update, context):
    query = update.callback_query
    await query.answer()
    user = update.effective_user
    await _reply(update, "🎫 <b>تیکت</b>\nموضوع را یک خط بنویس (مثلاً «فعال‌سازی نشد»):")
    if context.user_data is None:
        context.user_data = {}
    context.user_data["awaiting_ticket_subject"] = True


async def cb_ticket_subject(update, context):
    user = update.effective_user
    subject = (update.message.text or "").strip()
    if not subject:
        return
    await _reply(update, "✍️ پیام خود را بنویس و بفرست:")
    context.user_data["awaiting_ticket_body"] = True
    context.user_data["ticket_subject"] = subject


async def cb_account(update, context):
    query = update.callback_query
    await query.answer()
    user = update.effective_user
    conn = store.connect()
    try:
        row = conn.execute("SELECT * FROM users WHERE telegram_id=?", (user.id,)).fetchone()
        if row:
            text = f"👤 <b>حساب شما</b>\nشناسه: {row['id']}\nاطلاعات: تیکت و سفارش‌ها در همین ربات."
        else:
            text = "👤 <b>حساب شما</b>\nهنوز سفارشی ثبت نشده."
        await _reply(update, text)
    finally:
        conn.close()


async def cmd_account(update, context):
    await cb_account(update, context)


async def cmd_cart(update, context):
    await cb_cart(update, context)


async def cmd_ticket(update, context):
    user = update.effective_user
    await _reply(update, "🎫 <b>تیکت</b>\nموضوع را یک خط بنویس (مثلاً «فعال‌سازی نشد»):")
    context.user_data["awaiting_ticket_subject"] = True


async def cmd_pay(update, context):
    user = update.effective_user
    cart = _cart_lines(user.id)
    if not cart:
        await _reply(update, "سبد خرید خالی است.")
        return
    from .checkout import cb_checkout
    await cb_checkout(update, context)


async def cb_ticket_body(update, context):
    """Second step of the ticket flow: store the body and open the ticket."""
    user = update.effective_user
    body = (update.message.text or "").strip()
    if not body:
        await _reply(update, "پیام خالی است. دوباره بنویس:")
        return
    subject = context.user_data.get("ticket_subject", "بدون موضوع")
    from .tickets import create_ticket
    ticket_id = create_ticket(None, user.id, user.username or "", subject, body)
    context.user_data.pop("awaiting_ticket_subject", None)
    context.user_data.pop("awaiting_ticket_body", None)
    context.user_data.pop("ticket_subject", None)
    await _reply(update, f"✅ تیکت شما ثبت شد.\nشماره تیکت: <code>#{ticket_id}</code>\nپشتیبانی به‌زودی پاسخ می‌دهد.")

    admin_chat = int(store.get_setting("admin_chat_id", "0") or 0)
    if admin_chat:
        try:
            await context.bot.send_message(
                admin_chat,
                f"🎫 تیکت جدید #{ticket_id}\n👤 {_esc(user.username or user.id)}\n📌 {_esc(subject)}\n\n{_esc(body[:500])}",
            )
        except Exception:
            pass


async def handle_user_message(update, context):
    """Route free-text messages to the pending flow (ticket subject/body)."""
    text = (update.message.text or "").strip()
    if context.user_data.get("awaiting_ticket_body"):
        await cb_ticket_body(update, context)
        return
    if context.user_data.get("awaiting_ticket_subject"):
        await cb_ticket_subject(update, context)
        return
    if text.startswith("/"):
        return
    await _reply(update, "برای شروع یکی از دکمه‌های منو را بزن یا /start را بفرست.")