"""SkilarkApp: k9s-style full-screen terminal UI for Skilark."""

from pathlib import Path

from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Container
from textual.screen import ModalScreen
from textual.widgets import Footer, Static

from skilark_cli import __version__
from skilark_cli.client import SkilarkClient

CSS_PATH = Path(__file__).parent / "app.tcss"

TAB_LABELS = ["Drill", "Signals", "Jobs", "Profile"]


class HeaderBar(Static):
    """Top bar with app title and tab labels."""

    def __init__(self, active_index: int = 0) -> None:
        super().__init__(id="header-bar")
        self._active = active_index

    def set_active(self, index: int) -> None:
        self._active = index
        self._refresh_content()

    def on_mount(self) -> None:
        self._refresh_content()

    def _refresh_content(self) -> None:
        parts = [f"Skilark v{__version__}    "]
        for i, label in enumerate(TAB_LABELS):
            if i == self._active:
                parts.append(f"[reverse] [{i + 1}]{label} [/reverse]  ")
            else:
                parts.append(f"[{i + 1}]{label}  ")
        self.update("".join(parts))


class HelpScreen(ModalScreen):
    """Modal help screen that blocks all other input."""

    BINDINGS = [
        Binding("escape", "dismiss", "Close", show=False),
        Binding("question_mark", "dismiss", "Close", show=False),
    ]

    def compose(self) -> ComposeResult:
        yield Container(
            Static(
                "[bold]Keyboard Shortcuts[/bold]\n\n"
                "  [bold]1[/bold]  Drill (daily challenges)\n"
                "  [bold]2[/bold]  Market Signals\n"
                "  [bold]3[/bold]  Find My Fit (job search)\n"
                "  [bold]4[/bold]  Profile & Stats\n\n"
                "  [bold]q[/bold]  Quit\n"
                "  [bold]?[/bold]  Toggle this help\n\n"
                "Press [bold]Esc[/bold] or [bold]?[/bold] to close.",
                id="help-panel",
            ),
            id="help-overlay",
        )



class SkilarkApp(App):
    """Root application for the Skilark TUI."""

    TITLE = "Skilark"
    CSS_PATH = CSS_PATH

    BINDINGS = [
        Binding("1", "switch_tab(0)", "Drill", show=False, priority=True),
        Binding("2", "switch_tab(1)", "Signals", show=False, priority=True),
        Binding("3", "switch_tab(2)", "Jobs", show=False, priority=True),
        Binding("4", "switch_tab(3)", "Profile", show=False, priority=True),
        Binding("q", "quit_app", "Quit", priority=True),
        Binding("question_mark", "toggle_help", "Help", priority=True),
    ]

    def __init__(
        self,
        client: SkilarkClient | None = None,
        topics: list[str] | None = None,
        coding_language: str | None = None,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.client = client
        self.topics = topics or []
        self.coding_language = coding_language
        self._active_tab = 0  # Start on Drill

    def compose(self) -> ComposeResult:
        yield HeaderBar(active_index=self._active_tab)
        yield Container(id="content")
        yield Footer()

    async def on_mount(self) -> None:
        await self._switch_screen(self._active_tab)

    async def action_switch_tab(self, index: int) -> None:
        # Block tab switching while help modal is open
        if isinstance(self.screen, HelpScreen):
            return
        if index == self._active_tab:
            return
        self._active_tab = index
        self.query_one(HeaderBar).set_active(index)
        await self._switch_screen(index)

    async def _switch_screen(self, index: int) -> None:
        content = self.query_one("#content")
        await content.remove_children()

        if index == 0:
            from skilark_cli.tui.screens.drill import DrillPane

            await content.mount(
                DrillPane(
                    client=self.client,
                    topics=self.topics,
                    coding_language=self.coding_language,
                )
            )
        elif index == 1:
            from skilark_cli.tui.screens.signals import SignalsPane

            await content.mount(SignalsPane(client=self.client))
        elif index == 2:
            from skilark_cli.tui.screens.jobs import JobsPane

            await content.mount(JobsPane(client=self.client))
        elif index == 3:
            from skilark_cli.tui.screens.profile import ProfilePane

            await content.mount(ProfilePane(client=self.client))
        else:
            label = TAB_LABELS[index]
            await content.mount(
                Static(
                    f"\n\n[bold]{label}[/bold]\n\nComing soon.",
                    classes="placeholder-screen",
                )
            )

    def action_quit_app(self) -> None:
        # Block quit while help modal is open
        if isinstance(self.screen, HelpScreen):
            return
        self.exit()

    def action_toggle_help(self) -> None:
        if isinstance(self.screen, HelpScreen):
            self.screen.dismiss()
        else:
            self.push_screen(HelpScreen())
