"""
Agent Status Widget - Display agent status with rate limit progress.

Provides:
- Status emoji indicators
- Agent name display
- Usage progress bar
- Health indicators
"""

from typing import Optional

from textual.app import ComposeResult
from textual.containers import Vertical, Horizontal
from textual.widgets import Static, ProgressBar, Label
from textual.reactive import reactive
from rich.text import Text


class AgentStatusRow(Static):
    """Single agent status row with emoji, name, and usage bar."""

    DEFAULT_CSS = """
    AgentStatusRow {
        height: 3;
        layout: horizontal;
        padding: 0 1;
    }

    AgentStatusRow:hover {
        background: $surface-lighten-1;
    }

    AgentStatusRow.selected {
        background: $accent;
    }

    .status-indicator {
        width: 3;
        content-align: center middle;
    }

    .agent-name {
        width: 16;
        padding: 0 1;
    }

    .usage-container {
        width: 1fr;
    }

    .usage-bar {
        width: 100%;
    }

    .usage-text {
        width: 12;
        text-align: right;
    }

    .health-degraded {
        color: $warning;
    }

    .health-unhealthy {
        color: $error;
    }
    """

    # Status emoji mapping
    STATUS_EMOJIS = {
        "running": "🟢",
        "idle": "🟡",
        "paused": "⏸️",
        "exhausted": "🔴",
        "error": "❌",
        "unknown": "⚪",
    }

    agent_id: reactive[str] = reactive("")
    status: reactive[str] = reactive("unknown")
    health: reactive[str] = reactive("healthy")
    usage_percent: reactive[float] = reactive(0.0)
    is_selected: reactive[bool] = reactive(False)

    def __init__(
        self,
        agent_id: str = "",
        status: str = "unknown",
        health: str = "healthy",
        usage_percent: float = 0.0,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.agent_id = agent_id
        self.status = status
        self.health = health
        self.usage_percent = usage_percent

    def compose(self) -> ComposeResult:
        """Compose the row layout."""
        with Horizontal():
            yield Static(id="status-indicator", classes="status-indicator")
            yield Static(id="agent-name", classes="agent-name")
            with Horizontal(classes="usage-container"):
                yield ProgressBar(id="usage-bar", total=100, show_eta=False)
                yield Static(id="usage-text", classes="usage-text")

    def on_mount(self) -> None:
        """Initialize display on mount."""
        self._update_display()

    def watch_agent_id(self, value: str) -> None:
        """Update when agent_id changes."""
        self._update_display()

    def watch_status(self, value: str) -> None:
        """Update when status changes."""
        self._update_display()

    def watch_usage_percent(self, value: float) -> None:
        """Update when usage changes."""
        self._update_display()

    def watch_is_selected(self, value: bool) -> None:
        """Update selection styling."""
        self.set_class(value, "selected")

    def _update_display(self) -> None:
        """Update all display elements."""
        try:
            # Status emoji
            emoji = self.STATUS_EMOJIS.get(self.status, "⚪")
            self.query_one("#status-indicator", Static).update(emoji)

            # Agent name with health indicator
            name_text = self.agent_id
            if self.health == "degraded":
                name_text = f"[yellow]{self.agent_id}[/yellow]"
            elif self.health == "unhealthy":
                name_text = f"[red]{self.agent_id}[/red]"
            self.query_one("#agent-name", Static).update(name_text)

            # Usage bar
            bar = self.query_one("#usage-bar", ProgressBar)
            bar.progress = self.usage_percent

            # Usage text
            usage_text = f"[{self.usage_percent:.0f}%]"
            if self.usage_percent >= 90:
                usage_text = f"[red]{usage_text}[/red]"
            elif self.usage_percent >= 70:
                usage_text = f"[yellow]{usage_text}[/yellow]"
            self.query_one("#usage-text", Static).update(usage_text)

        except Exception:
            pass  # Widget not fully mounted yet

    def update_data(self, data: dict) -> None:
        """Update from data dictionary."""
        self.agent_id = data.get("agent_id", self.agent_id)
        self.status = data.get("status", self.status)
        self.health = data.get("health", self.health)
        self.usage_percent = data.get("usage_percent", self.usage_percent)


class AgentStatusPanel(Static):
    """Panel displaying all agent statuses."""

    DEFAULT_CSS = """
    AgentStatusPanel {
        height: 100%;
    }

    .panel-header {
        text-style: bold;
        margin-bottom: 1;
    }

    .agents-container {
        height: 1fr;
        overflow-y: auto;
    }

    .controls {
        height: 3;
        dock: bottom;
        padding: 0 1;
    }
    """

    selected_index: reactive[int] = reactive(0)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._agent_rows: list[AgentStatusRow] = []
        self._agent_data: list[dict] = []

    def compose(self) -> ComposeResult:
        """Compose the panel layout."""
        yield Static("AGENTS", classes="panel-header")
        yield Vertical(id="agents-container", classes="agents-container")
        yield Static(
            "[n]ew [p]ause [r]esume [k]ill",
            classes="controls",
        )

    def update_agents(self, agents: list[dict]) -> None:
        """Update agent status display."""
        self._agent_data = agents
        container = self.query_one("#agents-container", Vertical)

        # Remove old rows if count changed
        while len(self._agent_rows) > len(agents):
            row = self._agent_rows.pop()
            row.remove()

        # Add new rows if needed
        while len(self._agent_rows) < len(agents):
            row = AgentStatusRow()
            self._agent_rows.append(row)
            container.mount(row)

        # Update existing rows
        for i, (row, data) in enumerate(zip(self._agent_rows, agents)):
            row.update_data(data)
            row.is_selected = (i == self.selected_index)

    def select_next(self) -> None:
        """Select next agent."""
        if self._agent_data:
            self.selected_index = (self.selected_index + 1) % len(self._agent_data)
            self._update_selection()

    def select_previous(self) -> None:
        """Select previous agent."""
        if self._agent_data:
            self.selected_index = (self.selected_index - 1) % len(self._agent_data)
            self._update_selection()

    def _update_selection(self) -> None:
        """Update selection state on rows."""
        for i, row in enumerate(self._agent_rows):
            row.is_selected = (i == self.selected_index)

        # Notify parent of selection
        if self._agent_data and 0 <= self.selected_index < len(self._agent_data):
            agent_id = self._agent_data[self.selected_index].get("agent_id")
            self.app.selected_agent = agent_id

    def get_selected_agent(self) -> Optional[str]:
        """Get currently selected agent ID."""
        if self._agent_data and 0 <= self.selected_index < len(self._agent_data):
            return self._agent_data[self.selected_index].get("agent_id")
        return None
