"""
Task Queue Widget - Display pending and running tasks.

Provides:
- Task list with status indicators
- Assignment display
- Wait time tracking
- Interactive selection
"""

from typing import Optional

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.widgets import Static, DataTable
from textual.reactive import reactive


class TaskQueuePanel(Static):
    """Panel displaying task queue with status."""

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

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

    #task-table {
        height: 1fr;
    }

    .task-running {
        color: $success;
    }

    .task-queued {
        color: $warning;
    }

    .task-pending {
        color: $text-muted;
    }

    .task-failed {
        color: $error;
    }
    """

    selected_task: reactive[Optional[str]] = reactive(None)

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

    def compose(self) -> ComposeResult:
        """Compose the panel layout."""
        yield Static("TASK QUEUE", classes="panel-header")
        table = DataTable(id="task-table", cursor_type="row")
        table.add_columns("#", "Task", "Agent", "Status", "Wait")
        yield table

    def on_mount(self) -> None:
        """Configure table on mount."""
        table = self.query_one("#task-table", DataTable)
        table.cursor_type = "row"

    def update_tasks(self, tasks: list[dict]) -> None:
        """Update task queue display."""
        self._tasks = tasks
        table = self.query_one("#task-table", DataTable)

        # Clear existing rows
        table.clear()

        # Add rows with styling
        for i, task in enumerate(tasks, 1):
            status = task.get("status", "pending")
            description = task.get("description", "")[:35]
            agent = task.get("agent_id") or "-"
            wait = task.get("wait_time", "-")

            # Style based on status
            if status == "running":
                status_display = f"[green]{status}[/green]"
            elif status == "queued":
                status_display = f"[yellow]{status}[/yellow]"
            elif status == "failed":
                status_display = f"[red]{status}[/red]"
            else:
                status_display = f"[dim]{status}[/dim]"

            table.add_row(
                str(i),
                description,
                agent,
                status_display,
                wait,
                key=task.get("task_id", str(i)),
            )

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        """Handle row selection."""
        if event.row_key:
            self.selected_task = str(event.row_key.value)

    def get_selected_task(self) -> Optional[str]:
        """Get currently selected task ID."""
        return self.selected_task

    def get_task_count(self) -> int:
        """Get total task count."""
        return len(self._tasks)

    def get_pending_count(self) -> int:
        """Get count of pending tasks."""
        return sum(1 for t in self._tasks if t.get("status") in ("pending", "queued"))

    def get_running_count(self) -> int:
        """Get count of running tasks."""
        return sum(1 for t in self._tasks if t.get("status") == "running")
