"""Base navigation screen class for all main screens.

This module provides a base Screen class that includes:
- Global navigation keybindings (c, a, t, s, m, d) as priority bindings
- A persistent navigation footer
- Common screen lifecycle management

All main screens should inherit from NavScreen instead of Screen.
"""

from typing import TYPE_CHECKING, ClassVar

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import Screen
from textual.widgets import Static

if TYPE_CHECKING:
    from cli.tui.app import AlloyRuntimeApp


class NavFooter(Static):
    """Navigation footer showing available screens.

    Displays a persistent bar at the bottom showing which keys
    switch to which screens, with the current screen highlighted.
    """

    DEFAULT_CSS = """
    NavFooter {
        dock: bottom;
        height: 1;
        background: $surface-darken-1;
        color: $text-muted;
        padding: 0 1;
    }
    
    NavFooter .nav-item {
        margin-right: 2;
    }
    
    NavFooter .nav-active {
        color: $accent;
        text-style: bold;
    }
    """

    def __init__(self, active_screen: str = "") -> None:
        """Initialize the navigation footer.

        Args:
            active_screen: The ID of the currently active screen.
        """
        super().__init__()
        self._active = active_screen

    def compose(self) -> ComposeResult:
        """Render nothing - we use render() instead."""
        return
        yield  # Make this a generator

    def render(self) -> str:
        """Render the navigation bar."""
        items = [
            ("c", "Chat", "chat"),
            ("a", "Agents", "agents"),
            ("t", "Templates", "templates"),
            ("m", "Content", "content"),
            ("s", "Schemas", "schemas"),
            ("g", "Configs", "tool_configs"),
        ]

        parts: list[str] = []
        for key, label, screen_id in items:
            if screen_id == self._active:
                parts.append(f"[$accent bold][{key.upper()}] {label}[/]")
            else:
                parts.append(f"[dim][{key}][/] {label}")

        # Add help and quit
        parts.append("[dim][?][/] Help")
        parts.append("[dim][d][/] Dashboard")

        return "  ".join(parts)

    def set_active(self, screen_id: str) -> None:
        """Update the active screen indicator."""
        self._active = screen_id
        self.refresh()


class NavScreen(Screen[None]):
    """Base screen class with navigation keybindings.

    All main application screens should inherit from this class.
    It provides:
    - Global navigation bindings (c, a, t, s, m, d) as priority
    - Help modal binding (?)
    - Quit binding (Ctrl+C)
    - A navigation footer

    Subclasses must set SCREEN_ID class variable to identify themselves.

    Subclasses should:
    1. Override compose_content() instead of compose()
    2. Set SCREEN_ID to their identifier
    3. Define their own BINDINGS for screen-specific actions
    """

    app: "AlloyRuntimeApp"

    # Subclasses must set this to their screen ID
    SCREEN_ID: ClassVar[str] = ""

    # Navigation bindings - these are PRIORITY so they work regardless of focus
    # Single letter keys for fast switching between main screens
    BINDINGS = [
        # Global navigation - priority ensures these always work
        Binding("c", "switch_screen('chat')", "Chat", show=False, priority=True),
        Binding("a", "switch_screen('agents')", "Agents", show=False, priority=True),
        Binding(
            "t", "switch_screen('templates')", "Templates", show=False, priority=True
        ),
        Binding("m", "switch_screen('content')", "Content", show=False, priority=True),
        Binding("s", "switch_screen('schemas')", "Schemas", show=False, priority=True),
        Binding(
            "g",
            "switch_screen('tool_configs')",
            "Tool Configs",
            show=False,
            priority=True,
        ),
        Binding("d", "show_dashboard", "Dashboard", show=False, priority=True),
        Binding("question_mark", "show_help", "Help", show=False, priority=True),
        Binding("ctrl+c", "quit", "Quit", show=False, priority=True),
    ]

    def compose(self) -> ComposeResult:
        """Compose the screen layout with navigation footer.

        Subclasses should override compose_content() instead of this method.
        """
        with Vertical(id="screen-root"):
            yield from self.compose_content()
        yield NavFooter(active_screen=self.SCREEN_ID)

    def compose_content(self) -> ComposeResult:
        """Compose the main screen content.

        Subclasses must override this method to provide their content.
        """
        yield Static("Override compose_content() in your screen subclass")

    def on_screen_resume(self) -> None:
        """Called when this screen becomes active.

        Subclasses can override to set focus when returning to the screen.
        """
        pass

    def action_switch_screen(self, screen_id: str) -> None:
        """Switch to a different screen.

        Args:
            screen_id: The screen to switch to (chat, agents, templates, content, schemas)
        """
        if screen_id == self.SCREEN_ID:
            return  # Already on this screen
        self.app.switch_to_screen(screen_id)

    def action_show_dashboard(self) -> None:
        """Show the dashboard modal."""
        from cli.tui.screens.dashboard import DashboardScreen

        self.app.push_screen(DashboardScreen())

    def action_show_help(self) -> None:
        """Show the help modal."""
        from cli.tui.widgets.help_modal import HelpModal

        self.app.push_screen(HelpModal())

    def action_quit(self) -> None:
        """Quit the application."""
        self.app.exit()
