from textual.app import App
from textual.widgets import Header, Footer, Static
from textual.reactive import reactive
from textual import events
from .core import status


class DoctorChrome(App):
    """Keyboard-first TUI using Textual + Rich colors.

    Navigation: Up/Down or keys (1-5) to select, Enter to activate.
    Shortcuts: u=Upgrade Chrome, d=Upgrade Driver, m=Match Driver, r=Remove Driver, q=Quit
    """

    CSS = """
    Screen { align: center middle; background: $surface }
    #body { width: 80%; height: auto; border: round $primary; padding: 1 2 }
    .title { color: $accent; bold: true }
    .label { color: $text }
    .key { color: $success }
    .selected { background: $accent-dark; color: $text }
    """

    selected = reactive(0)
    message = reactive("")

    MENU = [
        ("Upgrade Chrome", "chrome", "u"),
        ("Upgrade Driver", "driver", "d"),
        ("Match Driver To Chrome", "match", "m"),
        ("Remove Driver", "remove", "r"),
        ("Exit", "exit", "q"),
    ]

    def compose(self):
        yield Header(show_clock=True)
        yield Static(id="body")
        yield Footer()

    def on_mount(self):
        self.refresh_body()

    def refresh_body(self):
        chrome, driver, state = status()
        chrome = chrome or "[red]Not found[/red]"
        driver = driver or "[red]Not found[/red]"

        lines = []
        lines.append("[bold cyan]Doctor Chrome[/bold cyan]\n")
        lines.append(f"[yellow]Chrome:[/yellow] {chrome}")
        lines.append(f"[yellow]Driver:[/yellow] {driver}")
        lines.append(f"[yellow]State:[/yellow] {state}\n")

        lines.append("[bold]Actions[/bold]")
        for idx, (label, _id, key) in enumerate(self.MENU):
            prefix = f"{idx+1}."
            if idx == self.selected:
                lines.append(f"[on #0f766e][white] {prefix} {label} ({key}) [/white][/on #0f766e]")
            else:
                lines.append(f"{prefix} [cyan]{label}[/cyan] ([green]{key}[/green])")

        if self.message:
            lines.append(f"\n[dim]{self.message}[/dim]")
        else:
            lines.append("\n[dim]Use Up/Down or 1-5 to select, Enter to activate. Press ? for help.[/dim]")

        body = self.query_one("#body", Static)
        body.update("\n".join(lines))

    async def on_key(self, event: events.Key) -> None:
        key = event.key
        if key in ("up", "k"):
            self.selected = max(0, self.selected - 1)
            self.refresh_body()
            return
        if key in ("down", "j"):
            self.selected = min(len(self.MENU) - 1, self.selected + 1)
            self.refresh_body()
            return
        if key.isdigit():
            n = int(key) - 1
            if 0 <= n < len(self.MENU):
                self.selected = n
                self.refresh_body()
            return
        if key in ("enter",):
            await self.activate(self.selected)
            return

        # direct shortcuts
        mapping = {k: i for i, (_, _id, k) in enumerate(self.MENU)}
        if key in mapping:
            idx = mapping[key]
            await self.activate(idx)
            return

        if key == "?":
            self.message = (
                "Shortcuts: up/down or k/j, numbers 1-5, u/d/m/r, Enter to run, q to quit."
            )
            self.refresh_body()
            return

    async def activate(self, idx: int):
        label, _id, key = self.MENU[idx]
        if _id == "exit":
            self.exit()
            return

        # Placeholder actions: core only provides `status()` today.
        # Show a brief message; actual operations can be implemented in `core.py` later.
        self.message = f"Action: {label} — not implemented in core.py"
        self.refresh_body()


def run():
    DoctorChrome().run()