"""Rich UI helpers - banner, tables, badges, messaging."""

from __future__ import annotations

from typing import Any

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.theme import Theme
from .config import DEFAULT_DNS_SERVER

# Shared console

THEME = Theme(
    {
        "banner": "bold cyan",
        "success": "bold green",
        "error": "bold red",
        "warning": "bold yellow",
        "info": "dim white",
        "muted": "grey62",
        "accent": "cyan",
        "status.active": "bold green",
        "status.inactive": "bold red",
        "status.pending": "bold yellow",
        "status.faulty": "bold red",
        "status.unknown": "grey62",
    }
)

console = Console(theme=THEME)
err_console = Console(stderr=True, theme=THEME)

# Banner

BANNER = r"""
 _____ _   _     _            _
| ____| |_| |__ (_) __ _  ___| | __
|  _| | __| '_ \| |/ _` |/ __| |/ /
| |___| |_| | | | | (_| | (__|   <
|_____|\__|_| |_|_|\__,_|\___|_|\_\  Beacon
"""


def print_banner(version: str) -> None:
    console.print(
        Panel(
            f"[banner]{BANNER.rstrip()}[/banner]\n"
            f"[muted]                                     v{version}[/muted]",
            border_style="cyan",
            padding=(0, 2),
        )
    )


# Status badge

STATUS_STYLES: dict[str, tuple[str, str]] = {
    "active": ("●", "status.active"),
    "inactive": ("●", "status.inactive"),
    "idle": ("●", "status.inactive"),
    "pending": ("◐", "status.pending"),
    "faulty": ("✗", "status.faulty"),
    "unknown": ("?", "status.unknown"),
}

_STATUS_INT_MAP: dict[int, str] = {
    1: "active",
    2: "idle",
    3: "faulty",
}


def status_badge(status: str | int) -> Text:
    if isinstance(status, int):
        status = _STATUS_INT_MAP.get(status, "unknown")
    icon, style = STATUS_STYLES.get(status.lower(), ("?", "status.unknown"))
    return Text(f"{icon} {status}", style=style)


# Beacon list table


def print_beacon_table(beacons: list[dict[str, Any]]) -> None:
    if not beacons:
        info("No beacons found. Run [accent]beacon create[/accent] to get started.")
        return

    table = Table(
        show_header=True,
        header_style="bold cyan",
        border_style="grey42",
        row_styles=["", "dim"],
        expand=False,
    )
    table.add_column("ID", style="muted", width=12, no_wrap=True)
    table.add_column("Name", style="bold white")
    table.add_column("Status", justify="center")
    table.add_column("CIDRs")
    table.add_column("Interface", style="accent")
    table.add_column("DNS", style="muted")
    table.add_column("Created", style="muted")

    for b in beacons:
        cidrs = ", ".join(b.get("allowed_cidrs") or [])
        created = (b.get("created", b.get("created_at", "")) or "")[:10]
        beacon_id = str(b.get("id", ""))
        dns_server = b.get("dns_server") or "-"
        if dns_server == DEFAULT_DNS_SERVER:
            dns_server = "auto"
        table.add_row(
            beacon_id,
            b.get("name", ""),
            status_badge(b.get("status", "unknown")),
            cidrs or "-",
            b.get("interface_name", "auto"),
            dns_server,
            created,
        )

    console.print(table)


# Beacon detail panel


def print_beacon_detail(b: dict[str, Any], local_running: bool = False) -> None:
    status = b.get("status", "unknown")
    if isinstance(status, int):
        status = _STATUS_INT_MAP.get(status, "unknown")
    lines = [
        f"[bold]ID[/bold]         {b.get('id', '')}",
        f"[bold]Name[/bold]       {b.get('name', '')}",
        f"[bold]Status[/bold]     {status_badge(status)}",
        f"[bold]Interface[/bold]  {b.get('interface_name', '')}",
        f"[bold]CIDRs[/bold]      {', '.join(b.get('allowed_cidrs', []))}",
        f"[bold]DNS[/bold]        {b.get('dns_server') or '-'}",
        f"[bold]Created[/bold]    {(b.get('created') or b.get('created_at') or '')[:19].replace('T', ' ')}",
    ]
    if "updated_at" in b:
        lines.append(
            f"[bold]Updated[/bold]    {b['updated_at'][:19].replace('T', ' ')}"
        )
    lines.append(f"[bold]Services[/bold]   {'[status.active]running[/]' if local_running else '[status.inactive]stopped[/]'} (local)")

    console.print(
        Panel(
            "\n".join(lines),
            title=f"[bold cyan]Beacon - {b.get('name', '')}[/bold cyan]",
            border_style="cyan",
            padding=(1, 2),
        )
    )


# Confirmation panel


def print_confirm_panel(title: str, rows: list[tuple[str, str]]) -> None:
    body = "\n".join(f"[bold]{k}[/bold]  {v}" for k, v in rows)
    console.print(
        Panel(body, title=f"[bold cyan]{title}[/bold cyan]", border_style="cyan", padding=(1, 2))
    )


# Message helpers


def success(msg: str) -> None:
    console.print(f"[success]✓[/success] {msg}")


def error(msg: str) -> None:
    err_console.print(f"[error]✗[/error] {msg}")


def warning(msg: str) -> None:
    console.print(f"[warning]⚠[/warning] {msg}")


def info(msg: str) -> None:
    console.print(f"[info]{msg}[/info]")


def step(msg: str) -> None:
    console.print(f"  [accent]→[/accent] {msg}")
