from __future__ import annotations

from textual import on, work
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.events import Key
from textual.screen import ModalScreen
from textual.widgets import Label, ListItem, ListView, Static


STATUSES = [
    ("available", "[green]\u2022[/]  available", "you're online"),
    ("away", "[yellow]\u2022[/]  away", "you'll get notifications"),
    ("dnd", "[red]\u2022[/]  do not disturb", "notifications silenced"),
]


class StatusOption(ListItem):
    def __init__(self, key: str, label: str, desc: str) -> None:
        super().__init__()
        self.status_key = key
        self._label = label
        self._desc = desc

    def compose(self) -> ComposeResult:
        yield Static(f"{self._label}  [dim]{self._desc}[/]")


class StatusScreen(ModalScreen[None]):

    def compose(self) -> ComposeResult:
        with Vertical(id="status-modal"):
            yield Label("set status", id="modal-title")
            yield ListView(id="status-list")

    async def on_mount(self) -> None:
        lv = self.query_one("#status-list", ListView)
        for key, label, desc in STATUSES:
            await lv.append(StatusOption(key, label, desc))

    @on(ListView.Selected, "#status-list")
    def on_selected(self, event: ListView.Selected) -> None:
        item = event.item
        if isinstance(item, StatusOption):
            self._set_status(item.status_key)

    @work(exclusive=True)
    async def _set_status(self, status: str) -> None:
        try:
            api = self.app.api
            await api.set_status(status)
            self.notify(f"status: {status}")
        except Exception:
            self.notify("failed", severity="error")
        self.dismiss(None)

    def on_key(self, event: Key) -> None:
        if event.key == "escape":
            event.stop()
            event.prevent_default()
            self.dismiss(None)
