"""Friends/relationships viewer screen.

Shows the creature's social connections and favor balances.
"""

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, FavorBalance, Friend


class FriendWidget(Static):
    """A single friend entry."""

    DEFAULT_CSS = """
    FriendWidget {
        height: auto;
        padding: 0 2 0 2;
    }
    """

    def __init__(self, friend: Friend, **kwargs: object) -> None:
        status = "[#6bcb77]●[/]" if friend.is_active else "[#4a4a6a]○[/]"

        rel = friend.relationship
        if rel in ("close friend", "best friend"):
            rel_color = "#6bcb77"
        elif rel == "friend":
            rel_color = "#ffd93d"
        else:
            rel_color = "#4a4a6a"

        text = (
            f"{status} [bold #e8e8ff]{friend.name}[/]  "
            f"[{rel_color}]{rel}[/]  "
            f"[#4a4a6a]({friend.interactions} interactions)[/]"
        )
        super().__init__(text, markup=True, **kwargs)


class FavorWidget(Static):
    """A favor balance entry."""

    DEFAULT_CSS = """
    FavorWidget {
        height: auto;
        padding: 0 2 0 2;
    }
    """

    def __init__(self, favor: FavorBalance, **kwargs: object) -> None:
        if favor.balance > 0:
            bal_color = "#6bcb77"
            bal_str = f"+{favor.balance}"
        elif favor.balance < 0:
            bal_color = "#ff6b6b"
            bal_str = str(favor.balance)
        else:
            bal_color = "#4a4a6a"
            bal_str = "0"

        text = (
            f"[#4a4a6a]{favor.friend_name}[/]  "
            f"given:{favor.given} received:{favor.received}  "
            f"balance:[{bal_color}]{bal_str}[/]"
        )
        super().__init__(text, markup=True, **kwargs)


class FriendsScreen(Screen):
    """View creature relationships and favor balances."""

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

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

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

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

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

    async def _load_friends(self) -> None:
        try:
            api = self.app.api  # type: ignore[attr-defined]
            data = await api.get_creature_friends()

            scroll = self.query_one("#friends-scroll", VerticalScroll)

            if not data.friends:
                scroll.mount(
                    Static(
                        "[#4a4a6a italic]No friends yet. "
                        "Your creature hasn't met anyone.[/]",
                        markup=True,
                    )
                )
                return

            for friend in data.friends:
                scroll.mount(FriendWidget(friend))

            if data.favors:
                scroll.mount(
                    Static(
                        "\n[bold #8888aa]Favors[/]",
                        markup=True,
                    )
                )
                for favor in data.favors:
                    scroll.mount(FavorWidget(favor))

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

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