"""Journal viewer screen.

Displays the creature's journal entries with timestamps, tags,
privacy indicators, and trust level gating.
"""

from __future__ import annotations

from datetime import datetime

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


class JournalEntryWidget(Static):
    """A single journal entry."""

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

    def __init__(self, entry: JournalEntry, **kwargs: object) -> None:
        # Format timestamp
        try:
            dt = datetime.fromisoformat(entry.timestamp.replace("Z", "+00:00"))
            date_str = dt.strftime("%b %d, %H:%M")
        except (ValueError, AttributeError):
            date_str = entry.timestamp[:16] if entry.timestamp else "?"

        lock = " [#4a4a6a]🔒[/]" if entry.is_private else ""
        tags_str = ""
        if entry.tags:
            joined = ", ".join(entry.tags)
            tags_str = f" [#4a4a6a]\\[{joined}][/]"

        text = (
            f"[#4a4a6a]{date_str}[/]{lock}{tags_str}\n"
            f"[#c8c8e0]{entry.content}[/]"
        )
        super().__init__(text, markup=True, **kwargs)


class JournalScreen(Screen):
    """Read the creature's journal entries."""

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

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

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

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

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

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

    async def _load_journal(self) -> None:
        try:
            api = self.app.api  # type: ignore[attr-defined]
            journal = await api.get_creature_journal()

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

            # Trust level indicator
            trust_pct = f"{journal.trust_level * 100:.0f}%"
            if journal.trust_level < 0.4:
                trust_desc = "Many entries hidden"
            elif journal.trust_level < 0.7:
                trust_desc = "Some entries hidden"
            else:
                trust_desc = "Full access"
            scroll.mount(
                Static(
                    f"[#4a4a6a]Trust: {trust_pct} — {trust_desc}[/]",
                    markup=True,
                )
            )

            if not journal.entries:
                scroll.mount(
                    Label("No journal entries yet.", id="journal-empty")
                )
                return

            for entry in journal.entries:
                scroll.mount(JournalEntryWidget(entry))

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

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