"""Session management screen widget for managing TUI sessions."""

from __future__ import annotations

import importlib
from dataclasses import dataclass
from typing import Any

__all__ = ["SessionInfo", "SessionManagementScreen"]


@dataclass(frozen=True, slots=True)
class SessionInfo:
    """Information about a single session."""

    session_id: str
    name: str
    message_count: int
    created_at: str


def _load_static_base() -> type[Any]:
    """Load the Textual Static widget base class."""
    try:
        return importlib.import_module("textual.widgets").Static
    except Exception:  # pragma: no cover

        class _FallbackStatic:
            def __init__(self, *args: object, **kwargs: object) -> None:
                self._text = ""

            def update(self, text: str) -> None:
                self._text = text

        return _FallbackStatic


_StaticBase = _load_static_base()


def _render_session_list(
    sessions: list[SessionInfo],
    selected_index: int,
    current_session_id: str,
) -> str:
    """Render the session list panel."""
    lines = [f"Sessions ({len(sessions)} total):"]
    for i, session in enumerate(sessions):
        prefix = "❯ " if i == selected_index else "  "  # noqa: RUF001
        current = " [CURRENT]" if session.session_id == current_session_id else ""
        lines.append(f"{prefix}{session.name} ({session.message_count} msgs){current}")
    return "\n".join(lines)


def _render_session_details(session: SessionInfo | None) -> str:
    """Render the session details panel."""
    if session is None:
        return "(no session selected)"

    lines = [
        f"Session: {session.name}",
        f"ID: {session.session_id}",
        f"Messages: {session.message_count}",
        f"Created: {session.created_at}",
    ]
    return "\n".join(lines)


def _render_status_bar() -> str:
    """Render the status bar at the bottom of the screen."""
    return "j/k Nav │ enter Switch │ r Rename │ d Delete │ n New │ esc Close"


def _render_screen(
    sessions: list[SessionInfo],
    selected_index: int,
    current_session_id: str,
) -> str:
    """Render the full SessionManagementScreen content as text."""
    session_list = _render_session_list(sessions, selected_index, current_session_id)
    selected_session = sessions[selected_index] if sessions else None
    session_details = _render_session_details(selected_session)
    status_bar = _render_status_bar()
    return f"Session Management\n\n{session_list}\n\n{session_details}\n\n{status_bar}"


class SessionManagementScreen(_StaticBase):
    """TUI widget for managing sessions.

    Allows users to:
    - View all sessions
    - Rename sessions
    - Delete sessions
    - Switch between sessions
    - Create new sessions

    Keyboard bindings:
    - ``j`` / ``k``: navigate session list (next / previous)
    - ``enter``: switch to selected session
    - ``r``: rename selected session
    - ``d``: delete selected session
    - ``n``: create new session
    - ``escape``: close session management screen
    """

    def __init__(self, *args: object, **kwargs: object) -> None:
        """Initialize the SessionManagementScreen."""
        super().__init__(*args, **kwargs)
        self._sessions: list[SessionInfo] = []
        self._selected_index: int = 0
        self._current_session_id: str = "default"
        self._text: str = ""
        self._visible: bool = False
        self._refresh()

    @property
    def visible(self) -> bool:
        """Return whether the session management screen is currently visible."""
        return self._visible

    @property
    def selected_index(self) -> int:
        """Return the index of the currently selected session."""
        return self._selected_index

    @property
    def current_session_id(self) -> str:
        """Return the ID of the currently active session."""
        return self._current_session_id

    @property
    def sessions(self) -> list[SessionInfo]:
        """Return the list of available sessions."""
        return self._sessions.copy()

    def show(self) -> None:
        """Show the session management screen."""
        self._visible = True
        self._refresh()

    def hide(self) -> None:
        """Hide the session management screen."""
        self._visible = False
        self._text = ""
        self.update("")

    def load_sessions(
        self, sessions: list[SessionInfo], current_session_id: str
    ) -> None:
        """Load a list of sessions and set the current session."""
        self._sessions = sessions
        self._current_session_id = current_session_id
        self._selected_index = 0
        self._refresh()

    def navigate_next(self) -> None:
        """Move selection to the next session (``j`` key)."""
        if self._sessions:
            self._selected_index = (self._selected_index + 1) % len(self._sessions)
            self._refresh()

    def navigate_prev(self) -> None:
        """Move selection to the previous session (``k`` key)."""
        if self._sessions:
            self._selected_index = (self._selected_index - 1) % len(self._sessions)
            self._refresh()

    def get_selected_session(self) -> SessionInfo | None:
        """Return the currently selected session, or None if no sessions."""
        if self._sessions and 0 <= self._selected_index < len(self._sessions):
            return self._sessions[self._selected_index]
        return None

    def _refresh(self) -> None:
        """Re-render the screen content."""
        if not self._visible:
            self._text = ""
            self.update("")
            return

        self._text = _render_screen(
            self._sessions,
            self._selected_index,
            self._current_session_id,
        )
        self.update(self._text)
