"""User-facing shop flows."""
import random
import string

import db
import i18n
import sepay
import tg
from i18n import money, t


def lang_of(uid):
    u = db.get_user(uid)
    return (u["lang"] if u and u["lang"] else "vi")


def home_kb(lang):
    return tg.ikb([
        [(t(lang, "menu_products"), "cats"), (t(lang, "menu_search"), "search")],
        [(t(lang, "menu_topup"), "topup"), (t(lang, "menu_balance"), "balance")],
        [(t(lang, "menu_orders"), "orders"), (t(lang, "menu_ref"), "ref")],
        [(t(lang, "menu_coupon"), "coupon"), (t(lang, "menu_support"), "support")],
        [(t(lang, "menu_lang"), "lang")],
    ])


def home_text(lang):
    return t(lang, "welcome", shop=db.get_setting("shop_name") or "Shop")


def show_home(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    if msg_id:
        res = tg.edit(chat_id, msg_id, home_text(lang), home_kb(lang))
        if res.get("ok"):
            return
    tg.send(chat_id, home_text(lang), home_kb(lang))


def show_categories(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    cats = db.categories()
    if not cats:
        txt = t(lang, "no_categories")
        kb = tg.ikb([[(t(lang, "menu_home"), "home")]])
    else:
        rows, row = [], []
        for c in cats:
            row.append(("%s %s" % (c["emoji"], c["name"]), "cat:%d:0" % c["id"]))
            if len(row) == 2:
                rows.append(row)
                row = []
        if row:
            rows.append(row)
        rows.append([(t(lang, "menu_home"), "home")])
        txt = t(lang, "categories")
        kb = tg.ikb(rows)
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def show_products(uid, chat_id, cat_id, page=0, msg_id=None):
    lang = lang_of(uid)
    cat = db.category(cat_id)
    if not cat:
        show_categories(uid, chat_id, msg_id)
        return
    per = 8
    rows_db, total = db.products_of(cat_id, page, per)
    pages = max(1, (total + per - 1) // per)
    if page >= pages:
        page = max(0, pages - 1)
        rows_db, total = db.products_of(cat_id, page, per)
    txt = t(lang, "products_title", cat="%s %s" % (cat["emoji"], cat["name"]),
            page=page + 1, pages=pages, total=total)
    if not rows_db:
        txt = t(lang, "no_products")
        kb = tg.ikb([[(t(lang, "back_cat"), "cats")], [(t(lang, "menu_home"), "home")]])
    else:
        rows = []
        for p in rows_db:
            stock = db.stock_count(p["id"])
            tag = "✅" if stock > 0 else "❌"
            rows.append([("%s %s · %s" % (tag, p["name"], money(p["price"])), "prod:%d" % p["id"])])
        nav = []
        if page > 0:
            nav.append((t(lang, "prev"), "cat:%d:%d" % (cat_id, page - 1)))
        if page + 1 < pages:
            nav.append((t(lang, "next"), "cat:%d:%d" % (cat_id, page + 1)))
        if nav:
            rows.append(nav)
        rows.append([(t(lang, "back_cat"), "cats")])
        kb = tg.ikb(rows)
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def product_card(uid, chat_id, pid, msg_id=None, note=""):
    lang = lang_of(uid)
    p = db.product(pid)
    if not p or not p["active"]:
        show_categories(uid, chat_id, msg_id)
        return
    stock = db.stock_count(pid)
    txt = t(lang, "product_card", name=tg.esc(p["name"]), price=money(p["price"]),
            stock=stock, desc=tg.esc(p["desc"] or ""))
    if note:
        txt += "\n\n" + note
    rows = []
    if stock > 0:
        rows.append([(t(lang, "buy_now"), "buy:%d" % pid)])
    else:
        rows.append([(t(lang, "out_of_stock"), "noop")])
    rows.append([(t(lang, "back_cat"), "cat:%d:0" % p["cat_id"])])
    kb = tg.ikb(rows)
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def calc_discount(uid, price):
    u = db.get_user(uid)
    code = (u["coupon"] or "").strip().upper() if u else ""
    if not code:
        return 0, None
    c = db.coupon(code)
    if not c:
        db.x("UPDATE users SET coupon=NULL WHERE id=?", (uid,))
        return 0, None
    if c["kind"] == "percent":
        d = price * c["value"] // 100
    else:
        d = c["value"]
    d = max(0, min(d, price))
    return d, code


def confirm_buy(uid, chat_id, pid, msg_id=None):
    lang = lang_of(uid)
    p = db.product(pid)
    if not p:
        show_categories(uid, chat_id, msg_id)
        return
    if db.stock_count(pid) <= 0:
        product_card(uid, chat_id, pid, msg_id, note=t(lang, "buy_oos"))
        return
    u = db.get_user(uid)
    disc, code = calc_discount(uid, p["price"])
    total = p["price"] - disc
    txt = t(lang, "confirm_buy", name=tg.esc(p["name"]), price=money(p["price"]),
            discount_line=(t(lang, "discount_line", discount=money(disc)) if disc else ""),
            total=money(total), balance=money(u["balance"]))
    kb = tg.ikb([
        [(t(lang, "yes"), "buyok:%d" % pid)],
        [(t(lang, "no"), "prod:%d" % pid)],
    ])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def do_buy(uid, chat_id, pid, msg_id=None):
    lang = lang_of(uid)
    p = db.product(pid)
    if not p:
        return
    if db.stock_count(pid) <= 0:
        product_card(uid, chat_id, pid, msg_id, note=t(lang, "buy_oos"))
        return
    u = db.get_user(uid)
    disc, code = calc_discount(uid, p["price"])
    total = p["price"] - disc
    if u["balance"] < total:
        kb = tg.ikb([[(t(lang, "menu_topup"), "topup")], [(t(lang, "menu_home"), "home")]])
        txt = t(lang, "buy_no_money", need=money(total), have=money(u["balance"]))
        if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
            return
        tg.send(chat_id, txt, kb)
        return

    # reserve stock atomically-ish: create order id placeholder first
    oid = db.x("INSERT INTO orders(user_id,product_id,product_name,price,discount,total,status,content,created_at) "
               "VALUES(?,?,?,?,?,?,'pending','',?)",
               (uid, pid, p["name"], p["price"], disc, total, db.now()))
    content = db.take_stock(pid, oid)
    if not content:
        db.x("UPDATE orders SET status='cancelled' WHERE id=?", (oid,))
        product_card(uid, chat_id, pid, msg_id, note=t(lang, "buy_oos"))
        return
    db.x("UPDATE orders SET status='done', content=? WHERE id=?", (content, oid))
    db.x("UPDATE products SET sold = sold + 1 WHERE id=?", (pid,))
    db.x("UPDATE users SET total_spent = total_spent + ?, balance = balance - ? WHERE id=?",
         (total, total, uid))
    db.x("INSERT INTO transactions(user_id,amount,type,note,created_at) VALUES(?,?,?,?,?)",
         (uid, -total, "buy", "order #%d %s" % (oid, p["name"]), db.now()))
    if code:
        db.use_coupon(code)
        db.x("UPDATE users SET coupon=NULL WHERE id=?", (uid,))

    txt = t(lang, "buy_ok", name=tg.esc(p["name"]), oid=oid, content=tg.esc(content))
    kb = tg.ikb([[(t(lang, "menu_home"), "home")]])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        pass
    else:
        tg.send(chat_id, txt, kb)

    # referral commission
    try:
        percent = int(db.get_setting("ref_percent", "5") or 0)
        if percent > 0 and u["ref_by"]:
            bonus = total * percent // 100
            if bonus > 0:
                db.add_balance(u["ref_by"], bonus, "ref", "commission from %s" % uid)
                ref = db.get_user(u["ref_by"])
                rl = (ref["lang"] if ref else "vi") or "vi"
                tg.send(u["ref_by"], t(rl, "ref_earn",
                                       name="%s" % (u["first_name"] or u["username"] or uid),
                                       amount=money(bonus)))
    except Exception as e:
        print("[ref] error:", e)

    for adm in db.q("SELECT id FROM users WHERE is_admin=1"):
        tg.send(adm["id"], "🛒 Đơn mới #%d · %s · %s · user <code>%s</code>"
                % (oid, p["name"], money(total), uid))


def show_balance(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    u = db.get_user(uid)
    orders = db.q1("SELECT COUNT(*) c FROM orders WHERE user_id=? AND status='done'", (uid,))["c"]
    refs = db.q1("SELECT COUNT(*) c FROM users WHERE ref_by=?", (uid,))["c"]
    tier = t(lang, "tier_vip") if u["total_spent"] >= 500000 else t(lang, "tier_new")
    txt = t(lang, "balance", uid=uid, tier=tier, balance=money(u["balance"]),
            orders=orders, refs=refs)
    kb = tg.ikb([[(t(lang, "menu_topup"), "topup")], [(t(lang, "menu_home"), "home")]])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def show_topup(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    amounts = [a.strip() for a in db.get_setting("topup_amounts", "").split(",") if a.strip()]
    rows, row = [], []
    for a in amounts:
        try:
            v = int(a)
        except Exception:
            continue
        row.append((money(v), "tup:%d" % v))
        if len(row) == 2:
            rows.append(row)
            row = []
    if row:
        rows.append(row)
    rows.append([(t(lang, "topup_custom"), "tup:custom")])
    rows.append([(t(lang, "menu_home"), "home")])
    txt = t(lang, "topup_title")
    kb = tg.ikb(rows)
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def gen_code(uid):
    alphabet = string.ascii_uppercase + string.digits
    for _ in range(20):
        code = "NAP%d%s" % (uid % 100000, "".join(random.choice(alphabet) for _ in range(5)))
        if not db.invoice_by_code(code):
            return code
    return "NAP%d%s" % (uid % 100000, "".join(random.choice(alphabet) for _ in range(6)))


def create_topup(uid, chat_id, amount, msg_id=None):
    lang = lang_of(uid)
    bank = db.get_setting("bank_name")
    account = db.get_setting("bank_account")
    holder = db.get_setting("bank_holder")
    if not account:
        kb = tg.ikb([[(t(lang, "menu_support"), "support")], [(t(lang, "menu_home"), "home")]])
        if msg_id and tg.edit(chat_id, msg_id, t(lang, "topup_no_bank"), kb).get("ok"):
            return
        tg.send(chat_id, t(lang, "topup_no_bank"), kb)
        return
    # reuse pending invoice of same amount
    inv = db.q1("SELECT * FROM invoices WHERE user_id=? AND status='pending' AND amount=? ORDER BY id DESC LIMIT 1",
                (uid, amount))
    if not inv:
        code = gen_code(uid)
        db.create_invoice(uid, code, amount)
        inv = db.invoice_by_code(code)
    txt = t(lang, "topup_invoice",
            amount=money(inv["amount"]), bank=tg.esc(bank or "-"),
            account=tg.esc(account), holder=tg.esc(holder or "-"),
            code=inv["code"], note=db.get_setting("bank_note") or t(lang, "topup_note_default"))
    kb = tg.ikb([
        [(t(lang, "topup_check"), "chk:%s" % inv["code"])],
        [(t(lang, "menu_home"), "home")],
    ])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def show_ref(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    count = db.q1("SELECT COUNT(*) c FROM users WHERE ref_by=?", (uid,))["c"]
    uname = getattr(tg, "BOT_USERNAME", "")
    link = "https://t.me/%s?start=ref_%d" % (uname, uid)
    txt = t(lang, "ref_info", percent=db.get_setting("ref_percent", "5"), link=link, count=count)
    kb = tg.ikb([[(t(lang, "menu_home"), "home")]])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def show_orders(uid, chat_id, msg_id=None):
    lang = lang_of(uid)
    rows_db = db.user_orders(uid, 10)
    if not rows_db:
        txt = t(lang, "orders_empty")
    else:
        txt = t(lang, "orders_title") + "\n"
        for o in rows_db:
            txt += t(lang, "order_line", oid=o["id"], name=tg.esc(o["product_name"]),
                     total=money(o["total"]), date=(o["created_at"] or "")[:16])
    kb = tg.ikb([[(t(lang, "menu_home"), "home")]])
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def show_lang(uid, chat_id, msg_id=None):
    kb = tg.ikb([
        [("🇻🇳 Tiếng Việt", "lang:vi"), ("🇬🇧 English", "lang:en")],
        [("◀️", "home")],
    ])
    txt = "🌐 Chọn ngôn ngữ / Choose language:"
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)


def search_results(uid, chat_id, query, msg_id=None):
    lang = lang_of(uid)
    q = "%" + query.strip() + "%"
    rows_db = db.q("SELECT * FROM products WHERE active=1 AND name LIKE ? ORDER BY id LIMIT 20", (q,))
    if not rows_db:
        txt = t(lang, "search_empty", q=tg.esc(query))
        kb = tg.ikb([[(t(lang, "menu_search"), "search")], [(t(lang, "menu_home"), "home")]])
    else:
        txt = t(lang, "search_result", q=tg.esc(query))
        rows = []
        for p in rows_db:
            stock = db.stock_count(p["id"])
            rows.append([("%s %s · %s" % ("✅" if stock else "❌", p["name"], money(p["price"])),
                          "prod:%d" % p["id"])])
        rows.append([(t(lang, "menu_home"), "home")])
        kb = tg.ikb(rows)
    if msg_id and tg.edit(chat_id, msg_id, txt, kb).get("ok"):
        return
    tg.send(chat_id, txt, kb)
