"""Group selection screen for filtering lessons by group."""

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.screen import Screen
from textual.widgets import Static, ListView, ListItem, Label
from textual.message import Message
from textual.binding import Binding
from textual import events


class GroupItem(ListItem):
    """A selectable group item."""
    
    def __init__(self, group: str, selected: bool = False) -> None:
        super().__init__()
        self.group = group
        self.selected = selected
    
    def compose(self) -> ComposeResult:
        prefix = "[X]" if self.selected else "[ ]"
        yield Label(f"{prefix} {self.group}")
    
    def toggle(self) -> None:
        self.selected = not self.selected
        prefix = "[X]" if self.selected else "[ ]"
        self.query_one(Label).update(f"{prefix} {self.group}")


class GroupSelectionScreen(Screen):
    """
    Screen for selecting which groups to display in the timetable.
    
    - Arrow keys: Navigate
    - Space: Toggle selection
    - Enter: Confirm and continue
    - Escape: Skip (show all)
    """
    
    BINDINGS = [
        Binding("escape", "skip", "Zobrazit vše"),
    ]
    
    DEFAULT_CSS = """
    GroupSelectionScreen {
        align: center middle;
    }
    
    GroupSelectionScreen > Vertical {
        width: 50;
        height: auto;
        max-height: 80%;
        padding: 1 2;
        border: round $primary;
        background: $surface;
    }
    
    GroupSelectionScreen .title {
        text-align: center;
        text-style: bold;
        color: $text;
        margin-bottom: 1;
    }
    
    GroupSelectionScreen .help-text {
        color: $text-muted;
        text-align: center;
        margin-bottom: 1;
    }
    
    GroupSelectionScreen ListView {
        height: auto;
        max-height: 15;
        margin: 1 0;
        background: $surface;
    }
    
    GroupSelectionScreen ListItem {
        padding: 0 1;
    }
    
    GroupSelectionScreen ListItem:hover {
        background: $primary-darken-2;
    }
    
    GroupSelectionScreen ListItem.-active {
        background: $primary;
    }
    
    GroupSelectionScreen .controls {
        color: $text-muted;
        text-align: center;
        margin-top: 1;
    }
    """
    
    class GroupsSelected(Message):
        """Message sent when groups are selected."""
        def __init__(self, groups: list[str]) -> None:
            self.groups = groups
            super().__init__()
    
    class Skipped(Message):
        """Message sent when user skips group selection."""
        pass
    
    def __init__(
        self,
        available_groups: list[str],
        selected_groups: list[str] | None = None,
        name: str | None = None,
    ) -> None:
        super().__init__(name=name)
        self._available_groups = available_groups
        self._selected: set[str] = set(selected_groups) if selected_groups else set()
    
    def compose(self) -> ComposeResult:
        """Create child widgets."""
        with Vertical():
            yield Static("Výběr skupin", classes="title")
            yield Static("Vyberte skupiny pro zobrazení:", classes="help-text")
            
            with ListView(id="group-list"):
                for group in self._available_groups:
                    yield GroupItem(group, group in self._selected)
            
            yield Static(
                "↑↓ pohyb | SPACE přepnout | ENTER potvrdit | ESC vše",
                classes="controls",
            )
    
    def on_mount(self) -> None:
        """Focus the list on mount."""
        self.query_one("#group-list", ListView).focus()
    
    def on_key(self, event: events.Key) -> None:
        """Handle key presses."""
        if event.key == "space":
            self._toggle_current()
            event.stop()
        elif event.key == "enter":
            self._confirm()
            event.stop()
    
    def _toggle_current(self) -> None:
        """Toggle the currently highlighted group."""
        list_view = self.query_one("#group-list", ListView)
        if list_view.highlighted_child is None:
            return
        
        item = list_view.highlighted_child
        if isinstance(item, GroupItem):
            item.toggle()
            if item.selected:
                self._selected.add(item.group)
            else:
                self._selected.discard(item.group)
    
    def _confirm(self) -> None:
        """Confirm selection and continue."""
        self.post_message(self.GroupsSelected(list(self._selected)))
    
    def action_skip(self) -> None:
        """Skip selection (show all groups)."""
        self.post_message(self.Skipped())
