"""
External Registries Tab for Infra TUI
"""

from textual.app import ComposeResult
from textual.widgets import Static, Label, Button, DataTable, Input
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from ..core.registry import RegistryManager, ExternalRegistry


class AddRegistryDialog(ModalScreen):
    """Dialog for adding a new external registry"""

    def __init__(self, app_instance):
        super().__init__()
        self.app_instance = app_instance

    def compose(self) -> ComposeResult:
        yield Vertical(
            Label("Add External Registry", id="add-reg-title"),
            Label("Name (unique identifier):", id="add-reg-name-label"),
            Input(placeholder="company-stacks", id="add-reg-name"),
            Label("Git URL:", id="add-reg-url-label"),
            Input(placeholder="https://github.com/org/stacks.git", id="add-reg-url"),
            Label("Branch (optional):", id="add-reg-branch-label"),
            Input(placeholder="main", id="add-reg-branch"),
            Horizontal(
                Button("Add", id="reg-submit", variant="primary"),
                Button("Cancel", id="reg-cancel", variant="default"),
                id="add-reg-buttons"
            ),
            id="add-reg-dialog"
        )

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "reg-cancel":
            self.dismiss(None)
            return

        if event.button.id == "reg-submit":
            name = self.query_one("#add-reg-name", Input).value.strip()
            url = self.query_one("#add-reg-url", Input).value.strip()
            branch = self.query_one("#add-reg-branch", Input).value.strip() or "main"

            if not name:
                self.app_instance.notify("Name is required", severity="error")
                return

            if not url:
                self.app_instance.notify("Git URL is required", severity="error")
                return

            self.dismiss({"name": name, "url": url, "branch": branch})

    CSS = """
    #add-reg-dialog {
        align: center middle;
        border: thick cyan;
        padding: 2;
        background: $surface;
        width: 70;
    }

    #add-reg-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    #add-reg-buttons {
        align: center middle;
        margin-top: 1;
    }

    Button {
        min-width: 12;
        margin: 0 1;
    }

    Input {
        margin-bottom: 1;
    }
    """


class RegistriesTab(Static):
    """Tab for managing external registries"""

    selected_registry: str | None = None

    def compose(self) -> ComposeResult:
        yield Label("External Registries", id="registries-title")
        yield Label(
            "Add external git repositories to install stacks from. "
            "Stacks appear under _external/{name}/ in the Registry tab.",
            id="registries-help"
        )
        yield Label("", id="registries-spacer1")

        yield DataTable(id="registries-table", cursor_type="row")

        yield Label("Selected: [dim]None[/]", id="registries-selected-label")

        yield Horizontal(
            Button("Add Registry", id="reg-add", variant="success"),
            Button("Sync", id="reg-sync", variant="primary", disabled=True),
            Button("Remove", id="reg-remove", variant="error", disabled=True),
            id="registries-buttons"
        )

    def on_mount(self) -> None:
        """Initialize registries table"""
        self.refresh_registries()

    def refresh_registries(self) -> None:
        """Refresh the registries table"""
        try:
            table = self.query_one("#registries-table", DataTable)
            table.clear(columns=True)
            table.add_column("Name", width=20, key="name")
            table.add_column("URL", width=45)
            table.add_column("Branch", width=12)
            table.add_column("Last Sync", width=20)

            registries = RegistryManager.list_external_registries()

            if not registries:
                table.add_row("(No external registries)", "", "", "", key="empty")
            else:
                for reg in registries:
                    # Format last sync
                    if reg.last_sync:
                        try:
                            from datetime import datetime
                            dt = datetime.fromisoformat(reg.last_sync)
                            last_sync = dt.strftime("%Y-%m-%d %H:%M")
                        except:
                            last_sync = reg.last_sync[:16]
                    else:
                        last_sync = "Never"

                    # Truncate URL if too long
                    url = reg.url
                    if len(url) > 43:
                        url = url[:40] + "..."

                    table.add_row(reg.name, url, reg.branch, last_sync, key=reg.name)

            # Reset selection
            self.selected_registry = None
            self.update_selected_label()
            self.update_button_states()

        except Exception as e:
            pass

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        """Handle row selection"""
        if event.data_table.id != "registries-table":
            return

        key = str(event.row_key.value) if event.row_key else None
        if key == "empty":
            self.selected_registry = None
        else:
            self.selected_registry = key

        self.update_selected_label()
        self.update_button_states()

    def update_selected_label(self) -> None:
        """Update the selected registry label"""
        try:
            label = self.query_one("#registries-selected-label", Label)
            if self.selected_registry:
                label.update(f"Selected: [bold]{self.selected_registry}[/]")
            else:
                label.update("Selected: [dim]None[/]")
        except Exception:
            pass

    def update_button_states(self) -> None:
        """Enable/disable buttons based on selection"""
        try:
            sync_btn = self.query_one("#reg-sync", Button)
            remove_btn = self.query_one("#reg-remove", Button)

            if self.selected_registry:
                sync_btn.disabled = False
                remove_btn.disabled = False
            else:
                sync_btn.disabled = True
                remove_btn.disabled = True
        except Exception:
            pass
