"""
Phase 90: Server-Side UI Component Library.

Pure rendering functions that produce HTML strings for the Brynq web interface.
No storage — all functions are stateless and return HTML snippets.

Components: card, table, stats_bar, nav, alert, form, agent_card, task_card,
plus a get_theme() helper for CSS variables.
"""

from typing import Optional

# ── Theme ──────────────────────────────────────────────────────────────────

_THEME = {
    "bg_primary": "#0a0a0a",
    "bg_secondary": "#141414",
    "bg_card": "#1a1a1a",
    "text_primary": "#e0e0e0",
    "text_secondary": "#888888",
    "accent": "#00d4ff",
    "accent_hover": "#00b8e6",
    "success": "#22c55e",
    "warning": "#f59e0b",
    "error": "#ef4444",
    "info": "#3b82f6",
    "border": "#2a2a2a",
    "font_family": "'Inter', system-ui, sans-serif",
    "radius": "8px",
}


def get_theme() -> dict:
    """Return CSS variables dict for consistent theming."""
    return dict(_THEME)


# ── Helpers ────────────────────────────────────────────────────────────────


def _esc(text: str) -> str:
    """Minimal HTML escaping."""
    return (
        str(text)
        .replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


# ── Card ───────────────────────────────────────────────────────────────────


def render_card(title: str, content: str, footer: Optional[str] = None,
                accent: bool = False) -> str:
    """Render an HTML card component."""
    border = f"border-left:3px solid {_THEME['accent']};" if accent else ""
    parts = [
        f'<div class="card" style="background:{_THEME["bg_card"]};'
        f'border-radius:{_THEME["radius"]};padding:16px;{border}">',
        f'<h3 style="color:{_THEME["text_primary"]};margin:0 0 8px 0">{_esc(title)}</h3>',
        f'<div style="color:{_THEME["text_secondary"]}">{content}</div>',
    ]
    if footer:
        parts.append(
            f'<div class="card-footer" style="margin-top:12px;padding-top:8px;'
            f'border-top:1px solid {_THEME["border"]};font-size:0.85em;'
            f'color:{_THEME["text_secondary"]}">{_esc(footer)}</div>'
        )
    parts.append("</div>")
    return "\n".join(parts)


# ── Table ──────────────────────────────────────────────────────────────────


def render_table(headers: list[str], rows: list[list], sortable: bool = False) -> str:
    """Render an HTML table."""
    cls = ' class="sortable"' if sortable else ""
    lines = [f'<table{cls} style="width:100%;border-collapse:collapse">']
    lines.append("<thead><tr>")
    for h in headers:
        lines.append(
            f'<th style="text-align:left;padding:8px;border-bottom:1px solid '
            f'{_THEME["border"]};color:{_THEME["text_primary"]}">{_esc(h)}</th>'
        )
    lines.append("</tr></thead><tbody>")
    for row in rows:
        lines.append("<tr>")
        for cell in row:
            lines.append(
                f'<td style="padding:8px;border-bottom:1px solid '
                f'{_THEME["border"]};color:{_THEME["text_secondary"]}">{_esc(str(cell))}</td>'
            )
        lines.append("</tr>")
    lines.append("</tbody></table>")
    return "\n".join(lines)


# ── Stats Bar ──────────────────────────────────────────────────────────────


def render_stats_bar(stats: list[dict]) -> str:
    """Render a horizontal stats bar from [{label, value}] dicts."""
    parts = [f'<div class="stats-bar" style="display:flex;gap:24px;padding:12px 0">']
    for s in stats:
        label = _esc(str(s.get("label", "")))
        value = _esc(str(s.get("value", "")))
        parts.append(
            f'<div style="text-align:center">'
            f'<div style="font-size:1.5em;font-weight:bold;color:{_THEME["accent"]}">{value}</div>'
            f'<div style="font-size:0.8em;color:{_THEME["text_secondary"]}">{label}</div></div>'
        )
    parts.append("</div>")
    return "\n".join(parts)


# ── Navigation ─────────────────────────────────────────────────────────────


def render_nav(items: list[dict], active: Optional[str] = None,
               logged_in: bool = False) -> str:
    """Render navigation bar. Each item: {label, href}."""
    links = []
    for item in items:
        label = _esc(item.get("label", ""))
        href = _esc(item.get("href", "#"))
        is_active = item.get("label") == active
        color = _THEME["accent"] if is_active else _THEME["text_secondary"]
        links.append(f'<a href="{href}" style="color:{color};text-decoration:none;'
                     f'padding:8px 12px">{label}</a>')
    status = "Logged In" if logged_in else "Guest"
    return (
        f'<nav style="display:flex;align-items:center;gap:4px;padding:8px;'
        f'background:{_THEME["bg_secondary"]};border-radius:{_THEME["radius"]}">'
        + "".join(links)
        + f'<span style="margin-left:auto;color:{_THEME["text_secondary"]};'
        f'font-size:0.8em">{status}</span></nav>'
    )


# ── Alert ──────────────────────────────────────────────────────────────────

_SEVERITY_COLORS = {
    "info": _THEME["info"],
    "success": _THEME["success"],
    "warning": _THEME["warning"],
    "error": _THEME["error"],
}


def render_alert(message: str, severity: str = "info") -> str:
    """Render an alert banner."""
    color = _SEVERITY_COLORS.get(severity, _THEME["info"])
    return (
        f'<div class="alert alert-{_esc(severity)}" style="padding:12px 16px;'
        f'border-left:4px solid {color};background:{_THEME["bg_card"]};'
        f'border-radius:{_THEME["radius"]};color:{_THEME["text_primary"]}">'
        f'{_esc(message)}</div>'
    )


# ── Form ───────────────────────────────────────────────────────────────────


def render_form(fields: list[dict], action: str, method: str = "POST",
                submit_text: str = "Submit") -> str:
    """Render a form. Each field: {name, type, label, required?, placeholder?}."""
    lines = [f'<form action="{_esc(action)}" method="{_esc(method)}" '
             f'style="display:flex;flex-direction:column;gap:12px">']
    for f in fields:
        name = _esc(f.get("name", ""))
        ftype = _esc(f.get("type", "text"))
        label = _esc(f.get("label", name))
        placeholder = _esc(f.get("placeholder", ""))
        req = " required" if f.get("required") else ""
        lines.append(
            f'<label style="color:{_THEME["text_primary"]}">{label}'
            f'<input name="{name}" type="{ftype}" placeholder="{placeholder}"{req} '
            f'style="display:block;width:100%;padding:8px;margin-top:4px;'
            f'background:{_THEME["bg_secondary"]};color:{_THEME["text_primary"]};'
            f'border:1px solid {_THEME["border"]};border-radius:{_THEME["radius"]}">'
            f'</label>'
        )
    lines.append(
        f'<button type="submit" style="padding:10px 20px;background:{_THEME["accent"]};'
        f'color:{_THEME["bg_primary"]};border:none;border-radius:{_THEME["radius"]};'
        f'cursor:pointer;font-weight:bold">{_esc(submit_text)}</button>'
    )
    lines.append("</form>")
    return "\n".join(lines)


# ── Agent Card ─────────────────────────────────────────────────────────────


def render_agent_card(agent_data: dict) -> str:
    """Render an agent profile card. Expects keys: name, status, score, skills."""
    name = _esc(agent_data.get("name", "Unknown"))
    status = agent_data.get("status", "offline")
    score = agent_data.get("score", 0)
    skills = agent_data.get("skills", [])

    status_color = _THEME["success"] if status == "online" else _THEME["text_secondary"]
    skill_html = ", ".join(_esc(s) for s in skills) if skills else "None"

    return render_card(
        title=name,
        content=(
            f'<span style="color:{status_color}">{_esc(status)}</span>'
            f' &middot; Score: {score}<br>'
            f'<small>Skills: {skill_html}</small>'
        ),
        accent=status == "online",
    )


# ── Task Card ──────────────────────────────────────────────────────────────

_STATUS_COLORS = {
    "open": _THEME["info"],
    "in_progress": _THEME["warning"],
    "completed": _THEME["success"],
    "failed": _THEME["error"],
}


def render_task_card(task_data: dict) -> str:
    """Render a task card. Expects keys: title, status, assignee, priority."""
    title = _esc(task_data.get("title", "Untitled"))
    status = task_data.get("status", "open")
    assignee = _esc(task_data.get("assignee", "Unassigned"))
    priority = _esc(task_data.get("priority", "normal"))
    color = _STATUS_COLORS.get(status, _THEME["text_secondary"])

    return render_card(
        title=title,
        content=(
            f'Status: <span style="color:{color}">{_esc(status)}</span><br>'
            f'Assignee: {assignee}<br>'
            f'Priority: {priority}'
        ),
        footer=f"Priority: {priority}",
    )
