"""Route summary widget."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Container
from textual.dom import NoMatches
from textual.reactive import var
from textual.widgets import DataTable, Label

from flux_networking_shared.tui.models.network import Route


class RouteSummary(Container):
    """Displays routing table in a DataTable."""

    BORDER_TITLE = "Route Summary"

    has_default_route = var(False)

    def __init__(self, routes: list[Route] | None = None) -> None:
        super().__init__()
        self.routes: list[Route] = routes or []

    def compose(self) -> ComposeResult:
        warning_label = Label(
            "No default route detected! This node will NOT be able to reach the internet",
            id="warning-label",
        )
        warning_label.display = False

        yield DataTable(cursor_type="none")
        yield warning_label

    def on_mount(self) -> None:
        self.update_table()

    def update_table(self) -> None:
        """Update the DataTable with current routes."""
        if not self.routes:
            return

        try:
            table = self.query_one(DataTable)
        except NoMatches:
            return

        table.clear(columns=True)

        columns = ["Dst", "Gateway", "Scope", "Proto", "Link", "Prefsrc"]
        rows = [x.data_row for x in self.routes]

        table.add_columns(*columns)
        table.add_rows(rows)

    def update_routes(self, routes: list[Route]) -> None:
        """Update routes and refresh display."""
        self.routes = routes
        self.has_default_route = any(x.is_default for x in self.routes)

        if self.is_mounted:
            self.update_table()

    def watch_has_default_route(self, has_route: bool) -> None:
        """Show/hide warning based on default route presence."""
        try:
            self.query_one("#warning-label", Label).display = not has_route
        except NoMatches:
            pass
