"""Network summary widget."""

from __future__ import annotations

from textual import on
from textual.app import ComposeResult
from textual.events import Key
from textual.widget import Widget

from flux_networking_shared.tui.messages import FocusTabsRequested
from flux_networking_shared.tui.widgets.interface_group import FocusButtonsRequested
from flux_networking_shared.tui.widgets.network_overview import NetworkOverview


class NetworkSummary(Widget, can_focus=True):
    """Container widget that displays network overview and connectivity status."""

    BORDER_TITLE = "Network Summary"

    DEFAULT_CSS = """
        NetworkSummary {
            height: auto;
            border: solid $primary;
            padding: 1;
        }

        NetworkSummary.--highlight {
            border: double $primary;
            background: $panel;
        }
    """

    def __init__(self) -> None:
        super().__init__()
        self.network_overview = NetworkOverview()

    def compose(self) -> ComposeResult:
        yield self.network_overview

    def on_key(self, event: Key) -> None:
        """Handle up/down navigation."""
        event_name = event.name

        if event_name not in ["up", "down"]:
            return

        event.stop()

        msg_cls = FocusTabsRequested if event_name == "up" else FocusButtonsRequested

        self.post_message(msg_cls())

    def set_network_address(self, address: str) -> None:
        """Set the primary network address."""
        self.network_overview.network_address = address

    def set_default_route(self, route: str) -> None:
        """Set the default route."""
        self.network_overview.default_route = route

    def set_dns(self, dns: str) -> None:
        """Set DNS server info."""
        self.network_overview.dns = dns

    def set_upnp_details(self, enabled: str, port: str) -> None:
        """Set UPnP status details."""
        self.network_overview.upnp_enabled = enabled
        self.network_overview.upnp_port = port

    def set_connectivity(self, state: str) -> None:
        """Set connectivity status."""
        self.network_overview.connectivity = state

    def set_name_resolution(self, state: str) -> None:
        """Set name resolution status."""
        self.network_overview.name_resolution = state

    def watch_has_focus(self, has_focus: bool) -> None:
        """Toggle highlight class on focus."""
        super().watch_has_focus(has_focus)
        self.set_class(has_focus, "--highlight")

    @on(NetworkOverview.NetworkAvailableMessage)
    def on_network_available(
        self, event: NetworkOverview.NetworkAvailableMessage
    ) -> None:
        """Handle network availability changes.

        When network becomes available, the parent screen may want to
        initiate connectivity tests to external services.
        """
        # Parent screen should handle this event to start/stop
        # connectivity monitoring as needed
        pass
