"""Creature switcher screen.

Lists all observer's creatures and allows switching the active one.
"""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import VerticalScroll
from textual.screen import Screen
from textual.widgets import Footer, Header, Label, Static

from sibilance.api.types import CreatureStatus


class CreatureCard(Static):
    """A clickable card for a single creature."""

    DEFAULT_CSS = """
    CreatureCard {
        height: auto;
        padding: 1 2;
        margin: 0 0 1 0;
        background: $surface;
        border: solid $secondary;
    }
    CreatureCard:hover {
        border: solid $primary;
    }
    CreatureCard .creature-card-name {
        color: $foreground;
        text-style: bold;
    }
    CreatureCard .creature-card-detail {
        color: $text-muted;
    }
    CreatureCard .creature-card-active {
        color: #6bcb77;
    }
    CreatureCard .creature-card-dormant {
        color: #ff6b6b;
    }
    """

    def __init__(self, creature: CreatureStatus, is_current: bool, **kwargs: object) -> None:
        self._creature = creature
        self._is_current = is_current
        super().__init__(**kwargs)

    def compose(self) -> ComposeResult:  # type: ignore[override]
        c = self._creature
        current_marker = " [current]" if self._is_current else ""
        yield Label(
            f"{c.name}{current_marker}",
            classes="creature-card-name",
        )

        status_cls = "creature-card-active" if c.is_active else "creature-card-dormant"
        status_text = "active" if c.is_active else "dormant"
        yield Label(status_text, classes=status_cls)

        details: list[str] = [f"Stage: {c.life_stage}"]
        if c.location:
            details.append(f"Location: {c.location}")
        if c.emotion:
            details.append(f"Feeling: {c.emotion.primary}")
        yield Label(" · ".join(details), classes="creature-card-detail")

    def on_click(self) -> None:
        if not self._is_current:
            self.screen.run_worker(
                self.screen._switch_creature(self._creature),  # type: ignore[attr-defined]
                name="switch-creature",
            )


class CreaturesScreen(Screen):
    """List and switch between creatures."""

    DEFAULT_CSS = """
    CreaturesScreen {
        layout: vertical;
    }

    #creatures-header {
        dock: top;
        height: 1;
        padding: 0 2;
        background: $surface;
        color: $primary;
        text-style: bold;
        border-bottom: solid $secondary;
    }

    #creatures-scroll {
        height: 1fr;
        background: $background;
        padding: 1 2;
        scrollbar-color: $secondary;
        scrollbar-color-hover: $text-muted;
        scrollbar-color-active: $primary;
    }

    #creatures-empty {
        color: $text-muted;
        text-style: italic;
        text-align: center;
        padding: 2;
    }
    """

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)
        yield Label("Your Creatures", id="creatures-header")
        yield VerticalScroll(id="creatures-scroll")
        yield Footer()

    def on_mount(self) -> None:
        self.run_worker(self._load_creatures(), name="load-creatures")

    async def _load_creatures(self) -> None:
        scroll = self.query_one("#creatures-scroll", VerticalScroll)
        scroll.remove_children()

        try:
            api = self.app.api  # type: ignore[attr-defined]
            creatures = await api.get_my_creatures()

            if not creatures:
                scroll.mount(
                    Label("No creatures. Complete the hatching ceremony first.", id="creatures-empty")
                )
                return

            current = self.app.creature  # type: ignore[attr-defined]
            current_id = current.agent_id if current else None

            for c in creatures:
                is_current = c.agent_id == current_id
                scroll.mount(CreatureCard(c, is_current))

        except Exception as exc:
            self.notify(f"Error: {exc}", severity="error", timeout=5)

    async def _switch_creature(self, creature: CreatureStatus) -> None:
        """Switch the active creature and return to dashboard."""
        self.app.creature = creature  # type: ignore[attr-defined]

        # Restart WebSocket for the new creature
        ws = getattr(self.app, "_ws", None)
        if ws:
            await ws.close()
        self.app._start_websocket()  # type: ignore[attr-defined]

        self.notify(f"Switched to {creature.name}", timeout=3)
        self.app.switch_screen("dashboard")  # type: ignore[attr-defined]

    def refresh_from_creature(self, creature: CreatureStatus) -> None:
        pass
