"""QuickActionsWidget - Mission Control HUD panel.

Contract: CNT-TUI-WDG-006
Traceability: UX-001, UI-002
"""

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


class ActionButton(Static):
    """Individual action button with icon, key, and label."""

    DEFAULT_CSS = """
    ActionButton {
        width: 1fr;
        height: 3;
        padding: 0 1;
        margin: 0;
    }

    ActionButton .action-content {
        width: 100%;
        height: 100%;
    }
    """

    def __init__(self, icon: str, key: str, label: str, description: str) -> None:
        super().__init__()
        self._icon = icon
        self._key = key
        self._label = label
        self._description = description

    def render(self) -> str:
        """Render the action button."""
        return (
            f"{self._icon} [bold #5eead4]\\[{self._key}][/] "
            f"[#e2e8f0]{self._label}[/]"
        )


class QuickActionsWidget(Static):
    """Mission Control HUD - Command center with visual shortcuts.

    Displays a grid of available actions with:
    - Visual icons for quick recognition
    - Highlighted key bindings
    - Clean grid layout
    """

    DEFAULT_CSS = """
    QuickActionsWidget {
        border: round #8b5cf6;
        padding: 1 1;
        margin: 0 1 1 1;
        height: auto;
        min-height: 8;
    }

    QuickActionsWidget #hud-title {
        text-align: center;
        text-style: bold;
        color: #a78bfa;
        margin-bottom: 1;
    }

    QuickActionsWidget #actions-grid {
        height: auto;
        padding: 0 1;
    }

    QuickActionsWidget .action-row {
        height: 2;
        width: 100%;
    }

    QuickActionsWidget .action-cell {
        width: 1fr;
        height: 2;
    }
    """

    # Action definitions: (icon, key, label, description)
    ACTIONS = [
        ("🚀", "^R", "Run Next", "Execute next phase/step"),
        ("📊", "^S", "Status", "Show project progress"),
        ("📝", "^E", "Edit", "Edit project context"),
        ("✅", "^V", "Validate", "Check artifacts"),
        ("🔐", "^L", "Login", "Claude Code auth"),
        ("🛑", "^C", "Stop", "Stop running process"),
        ("❓", "^H", "Help", "Show shortcuts"),
        ("🚪", "^Q", "Quit", "Exit Mission Control"),
    ]

    def __init__(self, is_executing: bool = False) -> None:
        """Initialize the HUD panel.

        Args:
            is_executing: Whether an execution is in progress
        """
        super().__init__()
        self._is_executing = is_executing

    def compose(self) -> ComposeResult:
        """Compose the HUD layout."""
        yield Static("⚡ QUICK ACTIONS", id="hud-title")

        with Vertical(id="actions-grid"):
            # Row 1: Primary actions
            with Horizontal(classes="action-row"):
                yield Static(self._format_action(0), classes="action-cell")
                yield Static(self._format_action(1), classes="action-cell")
                yield Static(self._format_action(2), classes="action-cell")
                yield Static(self._format_action(3), classes="action-cell")

            # Row 2: Secondary actions
            with Horizontal(classes="action-row"):
                yield Static(self._format_action(4), classes="action-cell")
                yield Static(self._format_action(5), classes="action-cell")
                yield Static(self._format_action(6), classes="action-cell")
                yield Static(self._format_action(7), classes="action-cell")

    def _format_action(self, index: int) -> str:
        """Format a single action for display.

        Args:
            index: Index into ACTIONS list

        Returns:
            Formatted action string with icon, key, and label
        """
        if index >= len(self.ACTIONS):
            return ""

        icon, key, label, _ = self.ACTIONS[index]

        # Dim disabled actions based on execution state
        if self._is_executing and key in ("^R", "^V", "^L"):
            # Can't run/validate/login during execution
            return f"[#64748b]{icon} \\[{key}] {label}[/]"

        if not self._is_executing and key == "^C":
            # Can't stop when nothing is running
            return f"[#64748b]{icon} \\[{key}] {label}[/]"

        return f"{icon} [bold #5eead4]\\[{key}][/] [#e2e8f0]{label}[/]"

    def set_executing(self, is_executing: bool) -> None:
        """Update execution state and refresh display.

        Args:
            is_executing: Whether execution is in progress
        """
        self._is_executing = is_executing
        self.refresh(recompose=True)
