"""Admin web panel (stdlib HTTP server)."""
import html
import json
import hashlib
import secrets
import time
from http.cookies import SimpleCookie
from urllib.parse import parse_qs

from . import store
from .auth import (SESSION_COOKIE, create_session, destroy_session, login as auth_login,
                   list_admins, create_admin, update_admin, delete_admin)
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)

PAGE = """<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
:root {{ --bg:#0f172a; --card:#1e293b; --line:#334155; --fg:#e2e8f0; --muted:#94a3b8; --accent:#38bdf8; --ok:#22c55e; --warn:#f59e0b; --bad:#ef4444; }}
* {{ box-sizing: border-box; }}
body {{ margin:0; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; background: var(--bg); color: var(--fg); font-size: 14px; line-height:1.5; }}
header {{ padding: 16px; border-bottom:1px solid var(--line); position: sticky; top:0; background: var(--bg); z-index:1; }}
h1 {{ font-size: 18px; margin:0 0 4px; }}
main {{ padding: 16px; max-width: 900px; margin: 0 auto; }}
.card {{ background: var(--card); border:1px solid var(--line); border-radius: 12px; padding: 14px; margin-bottom: 14px; }}
.row {{ display:flex; gap:10px; flex-wrap:wrap; }}
button {{ background:#2563eb; color:#fff; border:0; border-radius:10px; padding:10px 14px; font-size:14px; min-height:44px; cursor:pointer; }}
button.secondary {{ background:#334155; }}
button.danger {{ background:#b91c1c; }}
input, select, textarea {{ width:100%; background:#0b1220; color:var(--fg); border:1px solid var(--line); border-radius:10px; padding:10px 12px; font-size:16px; }}
label {{ display:block; margin:10px 0 4px; color:var(--muted); font-size:12px; }}
table {{ width:100%; border-collapse: collapse; font-size:12px; }}
th, td {{ text-align:right; padding:8px 6px; border-bottom:1px solid var(--line); }}
th {{ color:var(--muted); font-weight:600; }}
.badge {{ display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; border:1px solid var(--line); }}
.badge.ok {{ color:#86efac; border-color:#166534; }}
.badge.warn {{ color:#fcd34d; border-color:#92400e; }}
.badge.bad {{ color:#fca5a5; border-color:#991b1b; }}
.mono {{ font-family: ui-monospace, monospace; font-size:12px; background:#0b1220; padding:2px 6px; border-radius:6px; }}
.muted {{ color: var(--muted); }}
.msg {{ padding:10px 12px; border-radius:10px; margin-bottom:12px; border:1px solid var(--line); }}
.msg.ok {{ border-color:#166534; background:#052e16; }}
.msg.bad {{ border-color:#991b1b; background:#2a0a0a; }}
.msg.warn {{ border-color:#92400e; background:#2a1a05; }}
</style>
</head>
<body>
<header><h1>{title}</h1><div class="muted" id="who"></div></header>
<main id="app">{body}</main>
<script>
async function api(method, url, data) {{
  const opts = {{ method, headers: {{'Content-Type':'application/json'}} }};
  if (data) opts.body = JSON.stringify(data);
  const res = await fetch(url, opts);
  const text = await res.text();
  let json = null;
  try {{ json = text ? JSON.parse(text) : null; }} catch(e) {{ json = text; }}
  if (!res.ok) throw new Error((json && json.detail) || res.statusText || 'error');
  return json;
}}
function esc(s) {{ return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }}
function badge(status) {{
  const s = String(status||'');
  if (['paid','delivered','approved','active'].includes(s)) return '<span class="badge ok">'+esc(s)+'</span>';
  if (['pending','awaiting_admin','processing','in_progress'].includes(s)) return '<span class="badge warn">'+esc(s)+'</span>';
  if (['rejected','failed','cancelled','closed','disabled'].includes(s)) return '<span class="badge bad">'+esc(s)+'</span>';
  return '<span class="badge">'+esc(s)+'</span>';
}}
function money(n) {{ return Number(n||0).toLocaleString('fa-IR') + ' تومان'; }}
function toast(msg, kind) {{
  const el = document.createElement('div');
  el.className = 'msg ' + (kind||'ok');
  el.textContent = msg;
  document.getElementById('app').prepend(el);
  setTimeout(() => el.remove(), 5000);
}}
let sessionUsername = '';
let currentView = 'home';
function render(view, body, title) {{
  currentView = view;
  document.getElementById('app').innerHTML = body;
  document.getElementById('who').textContent = 'ورود: ' + (sessionUsername || 'unknown');
  window.scrollTo(0,0);
}}
function backBtn() {{ return '<button class="secondary" onclick="renderView(\'' + currentView + '\')">بازگشت</button>'; }}
async function boot() {{
  try {{
    const me = await api('GET','/api/me');
    sessionUsername = me.username;
    await renderView('home');
  }} catch (e) {{ location.href = '/login'; }}
}}
</script>
</body>
</html>
"""


def _page(title, body, status=200):
    return PAGE.format(title=title, body=body), status


def _html_escape(value):
    return html.escape(str(value))