"""HTML views for the admin panel."""
from .auth import list_admins
from .admin_api import (all_settings, approve_and_activate, close_ticket, create_service,
                        create_ticket, get_order, list_orders, list_services, list_tickets,
                        reject_order, reply_ticket, set_setting, update_service)
from .ui_components import badge, esc, kv, money, table


def view_home():
    orders = list_orders("pending", 10)
    tickets = list_tickets("open", 5)
    services = list_services()
    body = '<h2>خلاصه</h2><div class="row" style="margin:12px 0">'
    body += '<div class="card" style="flex:1 1 160px"><div class="muted">سفارش‌های در انتظار</div><div style="font-size:28px">%s</div></div>' % len(orders)
    body += '<div class="card" style="flex:1 1 160px"><div class="muted">تیکت‌های باز</div><div style="font-size:28px">%s</div></div>' % len(tickets)
    body += '<div class="card" style="flex:1 1 160px"><div class="muted">محصولات</div><div style="font-size:28px">%s</div></div>' % len(services)
    body += '</div>'
    body += '<div class="card"><h3>سفارش‌های اخیر</h3>' + table(
        ["#", "کاربر", "مبلغ", "روش", "وضعیت"],
        [[o["id"], esc(o["username"] or o["telegram_id"]), money(o["total_toman"]), esc(o["method"]), badge(o["status"])] for o in orders[:5]],
        "سفارشی ثبت نشده است")
    body += '</div>'
    body += '<div class="card"><h3>تیکت‌های باز</h3>' + table(
        ["#", "کاربر", "موضوع", "وضعیت"],
        [[t["id"], esc(t["username"] or t["telegram_id"]), esc((t["subject"] or "")[:50]), badge(t["status"])] for t in list_tickets("open", 5)],
        "تیکت بازی نیست")
    body += '</div>'
    body += '<div class="card"><h3>محصولات</h3>' + table(
        ["کد", "نام", "قیمت", "وضعیت"],
        [[s["code"], esc(s["name"]), money(s["price_toman"]), badge("active" if s["enabled"] else "disabled")] for s in services],
        "محصولی ثبت نشده است")
    body += '</div>'
    body += '<div class="row"><button onclick="renderView(\'orders\')">مشاهده همه سفارش‌ها</button>'
    body += '<button class="secondary" onclick="renderView(\'tickets\')">تیکت‌ها</button>'
    body += '<button class="secondary" onclick="renderView(\'services\')">مدیریت محصول</button></div>'
    return body


def view_orders():
    rows = list_orders(None, 50)
    body = "<h2>همه سفارش‌ها</h2>"
    body += table(["#", "کاربر", "مبلغ", "روش", "وضعیت", "کد"],
                  [[o["id"], esc(o["username"] or o["telegram_id"]), money(o["total_toman"]),
                    esc(o["method"]), badge(o["status"]),
                    ('<span class="mono">%s</span>' % esc(o["code"])) if o["code"] else ""] for o in rows],
                  "سفارشی ثبت نشده است")
    body += '<div class="row"><button class="secondary" onclick="renderView(\'home\')">بازگشت</button></div>'
    return body


def view_tickets():
    t = list_tickets(None, 50)
    body = "<h2>تیکت‌ها</h2>"
    rows = []
    for x in t:
        rows.append([x["id"], esc(x["username"] or x["telegram_id"]),
                     esc((x["subject"] or "")[:50]), badge(x["status"]),
                     ('<span class="mono">%s</span>' % esc(x["message"][:60])) if x["message"] else ""])
    body += table(["#", "کاربر", "موضوع", "وضعیت", "پیام"], rows, "تیکت فعالی نیست")
    body += '<div class="row"><button class="secondary" onclick="renderView(\'home\')">بازگشت</button></div>'
    return body


def view_services():
    services = list_services()
    body = "<h2>محصولات</h2>"
    body += '<div class="card"><h3>افزودن محصول</h3><form method="post" action="/api/services/create">'
    body += '<label>نام</label><input name="name" required placeholder="پنل وایرگارد VIP">'
    body += '<label>قیمت (تومان)</label><input name="price_toman" type="number" required min="0">'
    body += '<label>توضیح</label><textarea name="description" rows="3"></textarea>'
    body += '<label>rebecca service_id (اختیاری)</label><input name="rebecca_service_id" type="number">'
    body += '<label>inbound_tag (اختیاری)</label><input name="inbound_tag" placeholder="Vipazrwir">'
    body += '<button type="submit">افزودن</button></form></div>'
    rows = [[s["code"], esc(s["name"]), money(s["price_toman"]),
             badge("active" if s["enabled"] else "disabled"),
             ('<span class="mono">%s</span>' % esc(s["inbound_tag"])) if s["inbound_tag"] else ""] for s in services]
    body += '<div class="card"><h3>لیست محصولات</h3>' + table(["کد", "نام", "قیمت", "وضعیت", "inbound"], rows, "محصولی نیست") + '</div>'
    body += '<div class="row"><button class="secondary" onclick="renderView(\'home\')">بازگشت</button></div>'
    return body


def view_admins():
    admins = list_admins()
    rows = [[a["id"], esc(a["username"]), (a["telegram_id"] or ""), badge("active" if a["enabled"] else "disabled"), esc(a["role"])] for a in admins]
    body = "<h2>ادمین‌ها</h2>"
    body += '<div class="card"><h3>افزودن ادمین</h3><form method="post" action="/api/admins/create">'
    body += '<label>نام کاربری</label><input name="username" required>'
    body += '<label>رمز عبور</label><input type="password" name="password" required minlength="6">'
    body += '<label>Telegram ID (اختیاری)</label><input name="telegram_id" type="number">'
    body += '<button type="submit">افزودن</button></form></div>'
    body += '<div class="card"><h3>لیست</h3>' + table(["شناسه", "نام کاربری", "Telegram ID", "وضعیت", "نقش"], rows, "ادمینی نیست") + '</div>'
    body += '<div class="row"><button class="secondary" onclick="renderView(\'home\')">بازگشت</button></div>'
    return body


def view_settings():
    s = all_settings()
    body = "<h2>تنظیمات</h2>"
    body += '<div class="card"><h3>فرم تنظیمات</h3><form method="post" action="/api/settings/update">'
    body += '<label>نام فروشگاه</label><input name="shop_name" value="%s">' % esc(s.get("shop_name", ""))
    body += '<label>یوزرنیم پشتیبانی</label><input name="support_username" value="%s">' % esc(s.get("support_username", ""))
    body += '<button type="submit">ذخیره</button></form></div>'
    body += '<div class="card"><h3>مقادیر کلیدی</h3>' + table(["کلید", "مقدار"],
        [[esc(k), esc(s.get(k, ""))] for k in ["shop_name", "support_username", "card_approval_required",
         "crypto_approval_required", "rate_usd_toman", "min_order_toman", "payment_method_card",
         "payment_method_crypto", "payment_method_auto", "auto_approve_card", "auto_approve_crypto"]], "") + '</div>'
    body += '<div class="row"><button class="secondary" onclick="renderView(\'home\')">بازگشت</button></div>'
    return body