"""Content area widget.

Main scrollable content region for the TUI.
Displays different content types: text, mission lists, mission detail,
status (case board), briefing, completion message.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from rich.text import Text
from textual.containers import VerticalScroll
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Static

if TYPE_CHECKING:
    from textual.app import ComposeResult

    from unfamiliar.tui.themes import ThemeConfig
    from unfamiliar.tui.views import (
        BriefingData,
        CommandInfo,
        CompletionData,
        MissionDetail,
        MissionSummary,
        StatusData,
    )


class ContentArea(Widget):
    """Main scrollable content area for the TUI.

    Displays various content types with theme-aware styling.
    Methods to render different views:
    - show_text(markup): Render Rich markup text
    - show_missions(missions): Render mission list
    - show_mission_detail(detail): Render full mission view
    - show_status(data): Render case board
    - show_briefing(data): Render briefing
    - show_completion(data): Render completion message
    - clear(): Clear content

    Attributes:
        content: Reactive text content to display.
        theme: Theme configuration for vocabulary and styling.

    Note: Styling is defined in noir.tcss, not DEFAULT_CSS, to use theme variables.
    """

    content: reactive[str] = reactive("")

    def __init__(
        self,
        theme: ThemeConfig,
        *,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        """Initialize the content area.

        Args:
            theme: Theme configuration for vocabulary and styling.
            name: Widget name.
            id: Widget ID.
            classes: Space-separated CSS classes.
        """
        super().__init__(name=name, id=id, classes=classes)
        self.theme = theme

    def _c(self, key: str) -> str:
        """Shorthand for self.theme.color(key)."""
        return self.theme.color(key)

    def compose(self) -> ComposeResult:
        """Compose the content area layout."""
        yield VerticalScroll(
            Static("", id="content-body"),
            id="content-scroll",
        )

    def _get_body(self) -> Static:
        """Get the content body widget."""
        return self.query_one("#content-body", Static)

    def _clear_and_set(self, text: Text | str) -> None:
        """Clear content and set new text.

        Args:
            text: Text to display (Rich Text or string).
        """
        body = self._get_body()
        body.update(text)

    def show_text(self, markup: str) -> None:
        """Display Rich markup text.

        Args:
            markup: Rich markup string to render.
        """
        self._clear_and_set(Text.from_markup(markup))

    def show_missions(self, missions: list[MissionSummary]) -> None:
        """Display a list of available missions.

        Args:
            missions: List of mission summaries to display.
        """
        # Get themed terms
        mission_term = self.theme.vocab("mission")
        missions_term = self.theme.vocab("missions")
        available_term = self.theme.vocab("available")
        prerequisite_term = self.theme.vocab("prerequisite")

        if not missions:
            text = Text()
            text.append(
                f"No {missions_term} {available_term}.\n\n",
                style=f"italic {self._c('text_muted')}",
            )
            text.append(
                f"Complete {prerequisite_term}s to unlock more {missions_term}.",
                style=self._c("text_dim"),
            )
            self._clear_and_set(text)
            return

        text = Text()
        # Header uses themed terms: "Available Leads" or "Open Leads"
        text.append(
            f"{available_term.title()} {missions_term.title()}\n",
            style=f"bold {self._c('accent')}",
        )
        text.append("=" * 40 + "\n\n", style=self._c("divider"))

        for i, mission in enumerate(missions, 1):
            # Mission number and title
            text.append(f"[{i}] ", style=f"bold {self._c('accent')}")
            text.append(f"{mission.title}\n", style=self._c("text"))

            # Meta info
            meta_parts = []
            meta_parts.append(mission.category)
            meta_parts.append(f"{mission.difficulty}")
            meta_parts.append(f"{mission.time_minutes} min")
            text.append(f"    {' | '.join(meta_parts)}\n", style=self._c("text_muted"))

            # Security tag if present
            if mission.security_tag:
                text.append("    [SECURITY]\n", style=f"bold {self._c('warning')}")

            # Status indicator for in-progress missions
            if mission.status == "in_progress":
                status_term = self.theme.vocab("in_progress")
                text.append(
                    f"    [{status_term.upper()}]\n", style=f"bold {self._c('info')}"
                )

            text.append("\n")

        # Hint text uses themed command aliases
        next_alias = self.theme.alias("next")
        mission_alias = self.theme.alias("mission")
        text.append(
            f"Type '{next_alias} <N>' to start a {mission_term}, "
            f"or '{mission_alias} <N>' to peek.\n",
            style=f"dim {self._c('text_dim')}",
        )

        self._clear_and_set(text)

    def show_mission_detail(self, detail: MissionDetail) -> None:
        """Display detailed information for a single mission.

        Args:
            detail: Mission detail data to display.
        """
        # Get themed terms
        mission_term = self.theme.vocab("mission")
        file_ref_term = self.theme.vocab("file_ref")
        prereq_term = self.theme.vocab("prerequisite")

        text = Text()

        # Title
        text.append(f"{detail.title}\n", style=f"bold {self._c('accent')}")
        text.append("=" * 60 + "\n\n", style=self._c("divider"))

        # Status with themed label
        status_style = {
            "available": self._c("success"),
            "locked": self._c("warning"),
            "completed": f"dim {self._c('text_dim')}",
            "in_progress": self._c("info"),
        }.get(detail.status, self._c("text_muted"))

        # Get themed status term
        status_term = self.theme.vocab(detail.status)
        text.append("Status: ", style=self._c("text_muted"))
        text.append(f"{status_term.replace('_', ' ').title()}\n", style=status_style)

        # Category and difficulty
        text.append(
            f"Category: {detail.category} | Difficulty: {detail.difficulty} | ",
            style=self._c("text_muted"),
        )
        text.append(
            f"Time: ~{detail.time_minutes} min\n\n", style=self._c("text_muted")
        )

        # Narrative intro
        if detail.narrative_intro:
            text.append(
                f"{detail.narrative_intro}\n\n", style=f"italic {self._c('text_muted')}"
            )

        # Description
        text.append("Briefing\n", style=f"bold {self._c('accent')}")
        text.append(f"{detail.description}\n\n", style=self._c("text"))

        # Completion condition
        text.append("Completion Condition\n", style=f"bold {self._c('accent')}")
        text.append(f"{detail.completion_condition}\n\n", style=self._c("text"))

        # File references with themed header
        if detail.file_refs:
            text.append(
                f"{file_ref_term.title()} Files\n", style=f"bold {self._c('accent')}"
            )
            for ref in detail.file_refs:
                location = ref.file_path
                if ref.line_start is not None:
                    if ref.line_end is not None and ref.line_end != ref.line_start:
                        location += f":{ref.line_start}-{ref.line_end}"
                    else:
                        location += f":{ref.line_start}"
                text.append(f"  • {location}", style=self._c("text_muted"))
                if ref.description:
                    text.append(
                        f" — {ref.description}", style=f"dim {self._c('text_dim')}"
                    )
                text.append("\n")
            text.append("\n")

        # Prerequisites with themed header
        if detail.prerequisites:
            text.append(f"{prereq_term.title()}s\n", style=f"bold {self._c('accent')}")
            for prereq in detail.prerequisites:
                text.append(f"  • {prereq}\n", style=self._c("text_dim"))
            text.append("\n")

        # Security tag
        if detail.security_tag:
            text.append(
                f"[SECURITY-SENSITIVE] This {mission_term} "
                "involves security-relevant code.\n",
                style=f"bold {self._c('warning')}",
            )

        self._clear_and_set(text)

    def show_status(self, data: StatusData) -> None:
        """Display the case board (campaign status).

        Args:
            data: Status data to display.
        """
        # Get themed terms
        mission_term = self.theme.vocab("mission")
        missions_term = self.theme.vocab("missions")
        chains_term = self.theme.vocab("chains")
        category_term = self.theme.vocab("category")
        available_term = self.theme.vocab("available")
        in_progress_term = self.theme.vocab("in_progress")
        locked_term = self.theme.vocab("locked")
        completed_term = self.theme.vocab("completed")

        text = Text()

        # Header - themed: "Case Board" stays as-is for Film Noir
        text.append("Case Board\n", style=f"bold {self._c('accent')}")
        text.append("=" * 60 + "\n\n", style=self._c("divider"))

        # Overall progress
        text.append(f"{data.campaign_name}\n\n", style=self._c("text"))
        text.append("Overall Progress: ", style=self._c("text_muted"))
        text.append(f"{data.overall_percent}%\n", style=f"bold {self._c('accent')}")
        text.append(
            f"({data.completed}/{data.total} {missions_term} {completed_term})\n\n",
            style=self._c("text_muted"),
        )

        # Status breakdown with themed labels
        text.append(
            f"{mission_term.title()} Status\n", style=f"bold {self._c('accent')}"
        )
        text.append(
            f"  {available_term.title()}: {data.available}\n", style=self._c("success")
        )
        text.append(
            f"  {in_progress_term.title().replace('_', ' ')}: {data.in_progress}\n",
            style=self._c("info"),
        )
        text.append(
            f"  {locked_term.title()}: {data.locked}\n", style=self._c("warning")
        )
        text.append(
            f"  {completed_term.title()}: {data.completed}\n\n",
            style=f"dim {self._c('text_dim')}",
        )

        # Security summary
        if data.security_total > 0:
            text.append(
                f"Security {missions_term.title()}\n",
                style=f"bold {self._c('warning')}",
            )
            text.append(
                f"  {data.security_completed}/{data.security_total} "
                f"{completed_term}\n\n",
                style=self._c("text_muted"),
            )

        # Category breakdown with themed label
        text.append(f"By {category_term.title()}\n", style=f"bold {self._c('accent')}")
        for cat in data.categories:
            bar_filled = int(cat.percent / 10)
            bar_empty = 10 - bar_filled
            bar = "█" * bar_filled + "░" * bar_empty
            text.append(f"  {cat.display_name}:\n", style=self._c("text"))
            text.append(f"    [{bar}] {cat.percent}% ", style=self._c("text_muted"))
            text.append(
                f"({cat.completed}/{cat.total})\n", style=f"dim {self._c('text_dim')}"
            )
        text.append("\n")

        # Chains with themed label
        if data.chains:
            text.append(f"{chains_term.title()}\n", style=f"bold {self._c('accent')}")
            for chain in data.chains:
                status = "✓" if chain.completed_count == chain.mission_count else "○"
                text.append(
                    f"  {status} {chain.name}: ",
                    style=self._c("text"),
                )
                text.append(
                    f"{chain.completed_count}/{chain.mission_count}\n",
                    style=self._c("text_muted"),
                )

        self._clear_and_set(text)

    def show_briefing(self, data: BriefingData) -> None:
        """Display the briefing (case file) view.

        Args:
            data: Briefing data to display.
        """
        text = Text()

        text.append("Case File\n", style=f"bold {self._c('accent')}")
        text.append("=" * 60 + "\n\n", style=self._c("divider"))

        # Summary
        text.append("Intelligence Summary\n", style=f"bold {self._c('accent')}")
        text.append(f"{data.summary}\n\n", style=self._c("text"))

        # Tech stack
        if data.tech_stack:
            text.append("Technology Stack\n", style=f"bold {self._c('accent')}")
            for tech in data.tech_stack:
                text.append(f"  • {tech}\n", style=self._c("text_muted"))
            text.append("\n")

        # Security posture
        if data.security_posture:
            text.append("Security Assessment\n", style=f"bold {self._c('accent')}")
            text.append(f"{data.security_posture}\n", style=self._c("text"))

        self._clear_and_set(text)

    def show_completion(self, data: CompletionData) -> None:
        """Display mission completion message.

        Args:
            data: Completion data to display.
        """
        # Get themed terms
        mission_term = self.theme.vocab("mission")
        missions_term = self.theme.vocab("missions")
        completed_term = self.theme.vocab("completed")

        text = Text()

        # Header uses themed terms
        text.append(
            f"{mission_term.title()} {completed_term.title()}\n",
            style=f"bold {self._c('success')}",
        )
        text.append("=" * 60 + "\n\n", style=self._c("divider"))

        text.append(f"{data.mission_title}\n\n", style=self._c("text"))

        # Narrative outro
        if data.narrative_outro:
            text.append(
                f"{data.narrative_outro}\n\n", style=f"italic {self._c('text_muted')}"
            )

        # Unlocked missions
        if data.unlocked_titles:
            text.append(
                f"New {missions_term} unlocked:\n", style=f"bold {self._c('accent')}"
            )
            for title in data.unlocked_titles:
                text.append(f"  • {title}\n", style=self._c("success"))
            text.append("\n")

        # Progress summary
        text.append(
            f"Progress: {data.total_completed}/{data.total_missions} "
            f"{missions_term} {completed_term}\n",
            style=self._c("text_muted"),
        )

        self._clear_and_set(text)

    def show_error(self, message: str) -> None:
        """Display an error message.

        Args:
            message: Error message to display.
        """
        text = Text()
        text.append("Error\n", style=f"bold {self._c('error')}")
        text.append(f"{message}\n", style=self._c("text"))
        self._clear_and_set(text)

    def show_help(self, commands: list[CommandInfo]) -> None:
        """Display help with all commands in man-page style.

        Shows comprehensive reference with themed aliases prominently
        and canonical names as parenthetical reference.

        Args:
            commands: List of all available commands.
        """
        # Get themed terms
        campaign_term = self.theme.vocab("campaign")

        text = Text()

        # Title: man-page style
        text.append(
            f"UNFAMILIAR — {campaign_term.title()} Commands\n",
            style=f"bold {self._c('accent')}",
        )
        text.append("=" * 60 + "\n\n", style=self._c("divider"))

        # Commands section
        text.append("COMMANDS\n", style=f"bold {self._c('accent')}")
        text.append("-" * 60 + "\n\n", style=self._c("divider"))

        for cmd in commands:
            # Alias (bold) with canonical name (dim parenthetical)
            text.append(f"  {cmd.alias}", style=f"bold {self._c('text')}")
            text.append(f" ({cmd.canonical})\n", style=f"dim {self._c('text_dim')}")
            # Description indented
            text.append(f"    {cmd.description}\n\n", style=self._c("text_muted"))

        # Keyboard shortcuts section
        text.append("KEYBOARD SHORTCUTS\n", style=f"bold {self._c('accent')}")
        text.append("-" * 60 + "\n\n", style=self._c("divider"))

        # Use themed vocabulary in shortcut descriptions
        quit_alias = self.theme.alias("quit")
        help_alias = self.theme.alias("help")
        cancel_alias = self.theme.vocab("cancel")
        application_term = self.theme.vocab("application")

        shortcuts = [
            ("q", f"{quit_alias.title()} (exit the {application_term})"),
            ("?", f"{help_alias.title()} (show this reference)"),
            ("/", "Focus command input"),
            ("Tab", "Move focus between elements"),
            ("Escape", f"{cancel_alias.title()} (dismiss or defocus)"),
            ("←/→", "Navigate modal buttons"),
        ]

        for key, desc in shortcuts:
            text.append(f"  {key}", style=f"bold {self._c('text')}")
            text.append(f" — {desc}\n", style=self._c("text_muted"))

        self._clear_and_set(text)

    def clear(self) -> None:
        """Clear the content area."""
        self._clear_and_set("")


__all__ = ["ContentArea"]
