"""Main Textual application for Proxmox VM Template Builder."""

from __future__ import annotations

from pathlib import Path

from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import Footer, Header

from textual.widgets._toggle_button import ToggleButton

from tui.config import ConfigLoader
from tui.services import ProxmoxService, ScriptRunner

# Replace the default "X" toggle with a checkmark for SelectionList items
ToggleButton.BUTTON_INNER = "✓"


class LinuxAutomationApp(App):
    """Proxmox VM Template Builder TUI Application."""

    TITLE = "Proxmox VM Template Builder"
    CSS_PATH = "styles/app.tcss"

    BINDINGS = [
        Binding("q", "quit", "Quit", show=True),
        Binding("escape", "back", "Back", show=True),
        Binding("?", "help", "Help", show=False),
    ]

    def __init__(
        self,
        config_dir: str | Path | None = None,
        user_config_dir: str | Path | None = None,
    ):
        """Initialize the application.

        Args:
            config_dir: Path to bundled config directory.
            user_config_dir: Path to user's external config overrides.
                If provided, takes priority over env var and XDG default.
        """
        super().__init__()
        self.config = ConfigLoader(
            config_dir=config_dir,
            user_config_dir=user_config_dir,
        )
        self.proxmox = ProxmoxService()
        self.script_runner = ScriptRunner(
            user_config_dir=self.config.user_config_dir,
        )

    def compose(self) -> ComposeResult:
        yield Header()
        yield Footer()

    def on_mount(self) -> None:
        """Show setup wizard if creds missing, otherwise main menu."""
        if self.script_runner._find_packer_vars() is None:
            from tui.screens import SetupWizardScreen

            self.push_screen(SetupWizardScreen(from_menu=False))
        else:
            from tui.screens import MainMenuScreen

            self.push_screen(MainMenuScreen())

    def action_back(self) -> None:
        """Go back to previous screen."""
        if len(self.screen_stack) > 1:
            self.pop_screen()

    def action_help(self) -> None:
        """Show help dialog."""
        from tui.widgets.dialogs import MessageDialog

        help_text = """
Keyboard Shortcuts:
  b - Build new template
  a - Build all templates
  d - Deploy VM from template
  m - Manage VMs/templates
  q - Quit application
  Escape - Go back

Navigation:
  Enter - Select option
  Arrow keys - Navigate lists
  Space - Toggle selection (checklists)
  Tab - Next field
        """
        self.push_screen(MessageDialog("Help", help_text.strip()))
