from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import VerticalScroll
from textual.message import Message
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Label, ListItem, ListView, Static

from ..models import Workspace


class WorkspaceItem(ListItem):
    """A single workspace entry in the list."""

    def __init__(self, workspace: Workspace, **kwargs) -> None:
        super().__init__(**kwargs)
        self.workspace = workspace

    def compose(self) -> ComposeResult:
        ws = self.workspace
        # State indicator
        state = ws.agent_state
        if state == "running":
            icon = "[bold green]\u25cf[/]"
        elif state == "input":
            icon = "[bold yellow]\u25d0[/]"
        elif state == "idle":
            icon = "[dim]\u25cb[/]"
        else:
            icon = "[dim]\u2022[/]"

        # Selected marker
        sel = "[bold cyan]>[/] " if ws.selected else "  "

        # Notification badge
        unread = sum(1 for n in ws.notifications if not n.is_read)
        badge = f" [bold red]({unread})[/]" if unread else ""

        # Agent count
        agents = ws.agents
        agent_info = f" [magenta]{len(agents)}a[/]" if agents else ""

        # Branch
        branch = ""
        if ws.sidebar.git_branch and ws.sidebar.git_branch != "none":
            branch = f" [dim cyan]\u2387 {ws.sidebar.git_branch}[/]"

        label = f"{sel}{icon} {ws.title}{agent_info}{badge}{branch}"
        yield Static(label, markup=True)


class WorkspaceList(Widget):
    """Left panel showing all workspaces."""

    workspaces: reactive[list[Workspace]] = reactive(list, always_update=True)

    class Selected(Message):
        def __init__(self, workspace: Workspace) -> None:
            super().__init__()
            self.workspace = workspace

    def compose(self) -> ComposeResult:
        yield ListView(id="ws-list")

    def watch_workspaces(self, workspaces: list[Workspace]) -> None:
        lv = self.query_one("#ws-list", ListView)
        # Remember current index
        current_idx = lv.index or 0
        lv.clear()
        for ws in workspaces:
            lv.append(WorkspaceItem(ws))
        # Restore index
        if workspaces and current_idx < len(workspaces):
            lv.index = current_idx

    def on_list_view_selected(self, event: ListView.Selected) -> None:
        if isinstance(event.item, WorkspaceItem):
            self.post_message(self.Selected(event.item.workspace))

    def get_highlighted_workspace(self) -> Workspace | None:
        lv = self.query_one("#ws-list", ListView)
        if lv.index is not None and lv.index < len(self.workspaces):
            return self.workspaces[lv.index]
        return None
