from __future__ import annotations

from textual.app import ComposeResult
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Static

from ..models import Workspace


class DetailsPanel(Widget):
    """Shows details about the currently selected workspace."""

    workspace: reactive[Workspace | None] = reactive(None, always_update=True)

    def compose(self) -> ComposeResult:
        yield Static("", id="details-content")

    def watch_workspace(self, ws: Workspace | None) -> None:
        content = self.query_one("#details-content", Static)
        if ws is None:
            content.update("[dim]No workspace selected[/]")
            return

        sb = ws.sidebar
        lines = []
        lines.append(f"[bold cyan]{ws.title}[/] [dim]{ws.ref}[/]")
        lines.append("")

        # Agent state
        state = ws.agent_state
        if state == "running":
            lines.append("[green bold]\u25cf Running[/]")
        elif state == "input":
            lines.append("[yellow bold]\u25d0 Waiting for input[/]")
        elif state == "idle":
            lines.append("[dim]\u25cb Idle[/]")
        else:
            lines.append("[dim]No agent[/]")

        lines.append("")

        # Sidebar info
        if sb.cwd and sb.cwd != "none":
            short_cwd = sb.cwd.replace("/Users/aali", "~")
            lines.append(f"[dim]cwd:[/]  {short_cwd}")
        if sb.git_branch and sb.git_branch != "none":
            lines.append(f"[dim]git:[/]  \u2387 {sb.git_branch}")
        if sb.pr and sb.pr != "none":
            lines.append(f"[dim]pr:[/]   {sb.pr}")
        if sb.progress and sb.progress != "none":
            lines.append(f"[dim]prog:[/] {sb.progress}")
        if sb.ports and sb.ports != "none":
            lines.append(f"[dim]ports:[/] {sb.ports}")

        lines.append("")

        # Surfaces
        lines.append(f"[bold]Surfaces[/] ({ws.surface_count})")
        for pane in ws.panes:
            for surf in pane.surfaces:
                icon = "[magenta]\u2b22[/]" if surf.is_agent else "[dim]\u2022[/]"
                sel = " [cyan]*[/]" if surf.focused else ""
                stype = f"[dim]{surf.type}[/]"
                lines.append(f"  {icon} {surf.title}{sel} {stype}")

        # Notifications
        unread = [n for n in ws.notifications if not n.is_read]
        if unread:
            lines.append("")
            lines.append(f"[bold red]Notifications ({len(unread)})[/]")
            for n in unread[:3]:
                lines.append(f"  [yellow]{n.title}[/]: {n.body[:60]}")

        content.update("\n".join(lines))
