"""Interactive terminal UI for browsing scan results with arrow-key navigation."""

from __future__ import annotations

from typing import List

import readchar
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from ..engine.runner import Finding, ScanResult

console = Console()


def show_interactive(results: List[ScanResult]) -> None:
    """Arrow-key driven findings browser."""
    all_findings: List[tuple[str, Finding]] = []
    for result in results:
        platform_label = result.platform.value.upper()
        for finding in result.findings:
            all_findings.append((platform_label, finding))

    if not all_findings:
        console.print("\n  [bold #22c55e]No issues found \u2014 nothing to browse![/bold #22c55e]\n")
        readchar.readkey()
        return

    # Sort: FAILs first
    severity_order = {"FAIL": 0, "WARN": 1, "INFO": 2}
    all_findings.sort(key=lambda x: severity_order.get(x[1].severity, 3))

    selected = 0
    total = len(all_findings)
    page_size = 8
    mode = "list"  # "list" or "detail"

    while True:
        console.clear()

        if mode == "detail":
            _render_detail(all_findings[selected], selected, total)
            console.print("\n  [dim]Use \u2191\u2193 to switch findings, Esc/Backspace to go back, q to quit[/dim]")
        else:
            _render_list(all_findings, selected, page_size, total)
            console.print("\n  [dim]Use \u2191\u2193 to navigate, Enter for details, q to quit[/dim]")

        key = readchar.readkey()

        if key == readchar.key.UP:
            selected = (selected - 1) % total
        elif key == readchar.key.DOWN:
            selected = (selected + 1) % total
        elif key in (readchar.key.ENTER, "\r", "\n"):
            if mode == "list":
                mode = "detail"
            # In detail mode, Enter does nothing extra
        elif key in (readchar.key.ESC, readchar.key.BACKSPACE, "\x7f"):
            if mode == "detail":
                mode = "list"
            else:
                break
        elif key == "q":
            break


def _render_list(
    findings: List[tuple[str, Finding]],
    selected: int,
    page_size: int,
    total: int,
) -> None:
    """Render the scrollable findings list with cursor highlight."""
    # Calculate visible window
    half = page_size // 2
    if total <= page_size:
        start = 0
        end = total
    elif selected < half:
        start = 0
        end = page_size
    elif selected >= total - half:
        start = total - page_size
        end = total
    else:
        start = selected - half
        end = start + page_size

    severity_styles = {"FAIL": "#ef4444", "WARN": "#eab308", "INFO": "blue"}
    severity_icons = {"FAIL": "\u2718", "WARN": "\u26a0", "INFO": "\u2139"}

    header = (
        f"[bold]Findings Browser[/bold]  "
        f"[dim]({selected + 1}/{total})[/dim]"
    )

    lines: List[str] = []
    for i in range(start, end):
        platform, finding = findings[i]
        style = severity_styles.get(finding.severity, "")
        icon = severity_icons.get(finding.severity, " ")

        if i == selected:
            cursor = "[bold #eeef20]\u276f[/bold #eeef20]"
            line = (
                f"  {cursor} [{style}]{icon} {finding.severity}[/{style}]  "
                f"[bold]{finding.rule_id}[/bold]  {finding.message}"
            )
        else:
            line = (
                f"    [{style}]{icon} {finding.severity}[/{style}]  "
                f"[dim]{finding.rule_id}  {finding.message}[/dim]"
            )
        lines.append(line)

    # Scroll indicators
    if start > 0:
        lines.insert(0, "  [dim #eeef20]  \u25b2 more above[/dim #eeef20]")
    if end < total:
        lines.append("  [dim #eeef20]  \u25bc more below[/dim #eeef20]")

    body = "\n".join(lines)
    console.print(Panel(
        f"\n{body}\n",
        title=header,
        border_style="#eeef20",
        expand=False,
        padding=(0, 2),
    ))


def _render_detail(item: tuple[str, Finding], index: int, total: int) -> None:
    """Render the detail view for a single finding."""
    platform, finding = item
    severity_styles = {"FAIL": "#ef4444", "WARN": "#eab308", "INFO": "blue"}
    severity_icons = {"FAIL": "\u2718", "WARN": "\u26a0", "INFO": "\u2139"}
    style = severity_styles.get(finding.severity, "")
    icon = severity_icons.get(finding.severity, " ")

    detail = (
        f"\n"
        f"  [bold]Rule ID:[/bold]    {finding.rule_id}\n"
        f"  [bold]Severity:[/bold]   [{style}]{icon} {finding.severity}[/{style}]\n"
        f"  [bold]Platform:[/bold]   {platform}\n"
        f"\n"
        f"  [bold]Issue:[/bold]\n"
        f"  {finding.message}\n"
        f"\n"
        f"  [bold #22c55e]Fix:[/bold #22c55e]\n"
        f"  {finding.fix}\n"
    )
    if finding.reference:
        detail += (
            f"\n"
            f"  [bold blue]Reference:[/bold blue]\n"
            f"  [dim]{finding.reference}[/dim]\n"
        )

    console.print(Panel(
        detail,
        title=f"[bold]Finding Detail[/bold]  [dim]({index + 1}/{total})[/dim]",
        border_style="#eeef20",
        expand=False,
        padding=(0, 2),
    ))
