"""
Active Task Widget - Display currently running task details.

Provides:
- Task description and agent info
- Duration and progress tracking
- Token usage display
- Live output streaming
"""

from datetime import datetime
from typing import Optional

from textual.app import ComposeResult
from textual.containers import Vertical, Horizontal
from textual.widgets import Static, ProgressBar, RichLog
from textual.reactive import reactive


class ActiveTaskPanel(Static):
    """Panel displaying active task details and output."""

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

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

    #task-info {
        height: auto;
        padding: 1;
        border: solid $primary-lighten-2;
        margin-bottom: 1;
    }

    .info-row {
        height: 1;
        layout: horizontal;
    }

    .info-label {
        width: 10;
        color: $text-muted;
    }

    .info-value {
        width: 1fr;
    }

    #token-progress {
        margin: 1 0;
    }

    #task-output {
        height: 1fr;
        border: solid $secondary;
    }

    .no-task {
        color: $text-muted;
        text-align: center;
        padding: 3;
    }
    """

    has_task: reactive[bool] = reactive(False)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._task_data: Optional[dict] = None

    def compose(self) -> ComposeResult:
        """Compose the panel layout."""
        yield Static("ACTIVE TASK", classes="panel-header")

        with Vertical(id="task-info"):
            with Horizontal(classes="info-row"):
                yield Static("Task:", classes="info-label")
                yield Static(id="task-description", classes="info-value")

            with Horizontal(classes="info-row"):
                yield Static("Agent:", classes="info-label")
                yield Static(id="task-agent", classes="info-value")

            with Horizontal(classes="info-row"):
                yield Static("Status:", classes="info-label")
                yield Static(id="task-status", classes="info-value")

            with Horizontal(classes="info-row"):
                yield Static("Duration:", classes="info-label")
                yield Static(id="task-duration", classes="info-value")

            with Horizontal(classes="info-row"):
                yield Static("Tokens:", classes="info-label")
                yield Static(id="task-tokens", classes="info-value")

            yield ProgressBar(id="token-progress", total=100, show_eta=False)

        yield RichLog(id="task-output", highlight=True, markup=True)

    def update_task(self, task: Optional[dict]) -> None:
        """Update active task display."""
        self._task_data = task
        self.has_task = task is not None

        if not task:
            self._clear_display()
            return

        try:
            # Update info fields
            desc = task.get("description", "No description")[:50]
            self.query_one("#task-description", Static).update(desc)

            agent = task.get("agent_id", "None")
            self.query_one("#task-agent", Static).update(agent)

            status = task.get("status", "unknown")
            status_styled = self._style_status(status)
            self.query_one("#task-status", Static).update(status_styled)

            # Duration
            duration_secs = task.get("duration_seconds", 0)
            duration_str = self._format_duration(duration_secs)
            self.query_one("#task-duration", Static).update(duration_str)

            # Tokens
            tokens_used = task.get("tokens_used", 0)
            tokens_limit = task.get("tokens_limit", 1)
            tokens_str = f"{tokens_used:,} / {tokens_limit:,}"
            self.query_one("#task-tokens", Static).update(tokens_str)

            # Token progress
            token_percent = min(100, (tokens_used / tokens_limit) * 100) if tokens_limit > 0 else 0
            self.query_one("#token-progress", ProgressBar).progress = token_percent

            # Output log
            output_lines = task.get("output_lines", [])
            self._update_output(output_lines)

        except Exception:
            pass  # Widget not fully mounted

    def _clear_display(self) -> None:
        """Clear all display fields."""
        try:
            self.query_one("#task-description", Static).update("[dim]No active task[/dim]")
            self.query_one("#task-agent", Static).update("-")
            self.query_one("#task-status", Static).update("-")
            self.query_one("#task-duration", Static).update("-")
            self.query_one("#task-tokens", Static).update("-")
            self.query_one("#token-progress", ProgressBar).progress = 0
            self.query_one("#task-output", RichLog).clear()
        except Exception:
            pass

    def _style_status(self, status: str) -> str:
        """Apply styling to status text."""
        styles = {
            "running": f"[green]{status}[/green]",
            "completed": f"[blue]{status}[/blue]",
            "failed": f"[red]{status}[/red]",
            "paused": f"[yellow]{status}[/yellow]",
        }
        return styles.get(status, status)

    def _format_duration(self, seconds: int) -> str:
        """Format duration in human readable format."""
        if seconds < 60:
            return f"{seconds}s"
        elif seconds < 3600:
            mins = seconds // 60
            secs = seconds % 60
            return f"{mins}m {secs}s"
        else:
            hours = seconds // 3600
            mins = (seconds % 3600) // 60
            return f"{hours}h {mins}m"

    def _update_output(self, lines: list[str]) -> None:
        """Update output log with new lines."""
        log = self.query_one("#task-output", RichLog)

        # For now, just show last N lines
        # In real implementation, would stream incrementally
        log.clear()
        for line in lines[-20:]:  # Last 20 lines
            # Style output lines
            if line.startswith("✓"):
                log.write(f"[green]{line}[/green]")
            elif line.startswith("✗") or line.startswith("Error"):
                log.write(f"[red]{line}[/red]")
            elif line.startswith(">"):
                log.write(f"[blue]{line}[/blue]")
            else:
                log.write(line)

    def append_output(self, line: str) -> None:
        """Append a line to the output log."""
        log = self.query_one("#task-output", RichLog)
        log.write(line)

    def get_task_id(self) -> Optional[str]:
        """Get current task ID."""
        if self._task_data:
            return self._task_data.get("task_id")
        return None
