"""Den/territory viewer screen.

Displays the creature's dens, their condition, improvements, and descriptions.
"""

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, Den


def _condition_bar(condition: float, width: int = 12) -> str:
    """Render a condition bar (0..1)."""
    filled = round(max(0.0, min(1.0, condition)) * width)
    return "█" * filled + "░" * (width - filled)


def _condition_color(condition: float) -> str:
    if condition >= 0.7:
        return "#6bcb77"
    if condition >= 0.4:
        return "#ffd93d"
    return "#ff6b6b"


class DenWidget(Static):
    """A single den entry with condition bar and improvements."""

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

    def __init__(self, den: Den, **kwargs: object) -> None:
        color = _condition_color(den.condition)
        bar = _condition_bar(den.condition)
        pct = f"{den.condition * 100:.0f}%"

        lines: list[str] = [
            f"[bold #e8e8ff]{den.name}[/]  [#4a4a6a]@ {den.location}[/]",
            f"  [{color}]{bar}[/] [{color}]{pct}[/]",
        ]

        if den.description:
            lines.append(f"  [#c8c8e0]{den.description}[/]")

        if den.improvements:
            parts = [f"[#4ecdc4]{imp.name}[/]" for imp in den.improvements]
            lines.append(f"  Improvements: {', '.join(parts)}")

        super().__init__("\n".join(lines), markup=True, **kwargs)


class DenScreen(Screen):
    """View creature dens and territories."""

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

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

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

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)
        yield Label("Dens & Territories", id="den-header")
        yield VerticalScroll(id="den-scroll")
        yield Footer()

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

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

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

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

            # Also show territories from creature state
            creature = self.app.creature  # type: ignore[attr-defined]
            if creature and creature.territories:
                scroll.mount(
                    Static(
                        f"[#8888aa]Territories: {len(creature.territories)}[/]",
                        markup=True,
                    )
                )

            for den in data.dens:
                scroll.mount(DenWidget(den))

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

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