"""
TUI Application for Infra Services Management
Uses textual library for terminal UI
"""

import os
import subprocess
from textual.app import App, ComposeResult
from textual.widgets import (
    Header, Footer, Tabs, Tab, Static, Button, DataTable, Label, ContentSwitcher,
    TextArea, Markdown, Input
)
from textual.containers import Horizontal, Vertical, ScrollableContainer
from textual.binding import Binding
from textual.screen import ModalScreen
from textual import work
from pathlib import Path

# Core imports
from ..core.docker import DockerManager
from ..core.config import Config
from ..core.cloudflare import CloudflareManager
from ..core.users import UserManager
from ..core.host import HostManager
from ..core.registry import RegistryManager

# Tab imports
from .host_tab import HostTab
from .cloudflare_tab import CloudflareTab
from .registry_tab import RegistryTab
from .registries_tab import RegistriesTab, AddRegistryDialog
from .settings_tab import SettingsTab
from .system_tab import SystemTab
from .services_tab import ServicesTab
from .users_tab import UsersTab
from .ssh_tab import SSHTab
from .help_tab import HelpTab

# Dialog imports
from .dialogs import (
    ConfirmDialog,
    SelectUserTypeDialog,
    EnterUsernameDialog,
    SetPasswordDialog,
    SudoPasswordDialog,
    SSHTestDialog,
    SSHKeySetupDialog,
    InitialSetupDialog,
)


class InfraTUI(App):
    """Main TUI Application with Tabs"""

    CSS = """
    Screen {
        layout: vertical;
    }

    Tabs {
        dock: top;
    }

    ServicesTab, CloudflareTab, UsersTab, HostTab, SystemTab, HelpTab, SSHTab, RegistryTab, RegistriesTab {
        padding: 1;
    }

    #status-title, #cf-title, #users-title, #group-name, #users-help,
    #host-title, #host-help, #sysinfo-title, #system-title, #system-help,
    #help-title, #help-content, #ssh-title, #ssh-help, #ssh-config-title,
    #ssh-users-title, #registry-title, #registry-help, #registries-title,
    #registries-help {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    #help-content {
        text-align: left;
    }

    #users-help, #host-help, #cf-help, #system-help, #registry-help, #registries-help {
        color: $text-muted;
        margin: 1 0;
    }

    #registries-table {
        height: 1fr;
    }

    #registries-selected-label {
        text-align: center;
        margin: 1 0;
    }

    #registries-buttons {
        align: center middle;
        margin: 1 0;
    }

    #registries-spacer1 {
        height: 1;
    }

    #registry-category-buttons, #registry-action-buttons {
        align: center middle;
        margin: 1 0;
    }

    #registry-selected-label {
        text-align: center;
        margin: 1 0;
    }

    #registry-table {
        height: 1fr;
    }

    #registry-spacer1 {
        height: 1;
    }

    #users-header, #users-list Horizontal {
        height: auto;
        padding: 0 1;
    }

    #users-header Label {
        text-style: bold;
    }

    #users-list {
        height: 1fr;
    }

    /* Consistent column widths for header and content */
    .col-username { width: 14; min-width: 14; margin: 0 1; }
    .col-group, .col-group-btn { width: 9; min-width: 9; margin: 0 1; }
    .col-docker, .col-docker-btn { width: 9; min-width: 9; margin: 0 1; }
    .col-sudo, .col-add-sudo-btn { width: 7; min-width: 7; margin: 0 1; }
    .col-nopass, .col-sudo-btn, .col-sudo-placeholder { width: 9; min-width: 9; margin: 0 1; text-align: center; }
    .col-passwd, .col-passwd-btn { width: 8; min-width: 8; margin: 0 1; }
    .col-delete, .col-delete-btn { width: 12; min-width: 12; margin: 0 1; }

    #spacer {
        margin-top: 2;
    }

    #group-name {
        color: cyan;
    }

    #users-help {
        color: $text-muted;
        margin: 1 0;
    }

    #users-spacer, #users-spacer2, #ssh-spacer {
        height: 1;
    }

    #users-buttons, #create-user-container {
        align: center middle;
        margin-top: 1;
    }

    #ssh-global-buttons, #ssh-user-buttons {
        align: center middle;
        margin: 1 0;
    }

    #ssh-selected-label {
        text-align: center;
        margin: 1 0;
        color: $text;
    }

    #ssh-config-table {
        height: auto;
        max-height: 8;
    }

    #ssh-users-table {
        height: 1fr;
    }

    DataTable {
        height: 1fr;
    }

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

    Horizontal {
        height: auto;
        align: center middle;
        margin: 1 0;
    }

    Content {
        height: 1fr;
    }
    """

    TITLE = "Infra Services Management"

    BINDINGS = [
        Binding("q", "quit", "Quit", show=True),
        Binding("r", "refresh", "Refresh", show=True),
        Binding("1", "switch_tab('system')", "System", show=True),
        Binding("2", "switch_tab('services')", "Docker", show=True),
        Binding("3", "switch_tab('registry')", "Registry", show=True),
        Binding("4", "switch_tab('host')", "Host", show=True),
        Binding("5", "switch_tab('cloudflare')", "Cloudflare", show=True),
        Binding("6", "switch_tab('users')", "Users", show=True),
        Binding("7", "switch_tab('ssh')", "SSH", show=True),
        Binding("8", "switch_tab('settings')", "Settings", show=True),
        Binding("9", "switch_tab('help')", "Help", show=True),
        Binding("delete", "remove_user", "Remove", show=False),
    ]

    def compose(self) -> ComposeResult:
        yield Header()
        yield Tabs(
            Tab("System", id="system-tab"),
            Tab("Docker", id="services-tab"),
            Tab("Registry", id="registry-tab"),
            Tab("Registries", id="registries-tab"),
            Tab("Host", id="host-tab"),
            Tab("Cloudflare", id="cloudflare-tab"),
            Tab("Users", id="users-tab"),
            Tab("SSH", id="ssh-tab"),
            Tab("Settings", id="settings-tab"),
            Tab("Help", id="help-tab"),
        )
        yield ContentSwitcher(
            SystemTab(id="system-content"),
            ServicesTab(id="services-content"),
            RegistryTab(id="registry-content"),
            RegistriesTab(id="registries-content"),
            HostTab(id="host-content"),
            CloudflareTab(id="cloudflare-content"),
            UsersTab(id="users-content"),
            SSHTab(id="ssh-content"),
            SettingsTab(id="settings-content"),
            HelpTab(id="help-content"),
            id="content-switcher",
        )
        yield Footer()

    def on_mount(self) -> None:
        """Initialize the UI and check for initial setup"""
        # Initialize sudo password storage
        self.sudo_password = None

        # Cache sudo credentials if possible
        self.cache_sudo_credentials()

    def cache_sudo_credentials(self) -> None:
        """Attempt to cache sudo credentials by running sudo -v"""
        try:
            # Check if we can sudo without password first
            result = subprocess.run(
                ["sudo", "-n", "true"],
                capture_output=True,
                timeout=5
            )
            if result.returncode == 0:
                # Already have passwordless sudo, no need to prompt
                self.finish_initialization()
                return

            # Need password - show dialog and cache credentials
            def on_password(password):
                if password:
                    # Cache the credentials using sudo -v with stdin
                    try:
                        process = subprocess.Popen(
                            ["sudo", "-S", "-v"],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True
                        )
                        stdout, stderr = process.communicate(input=password + "\n")
                        if process.returncode != 0:
                            self.notify("Invalid sudo password", severity="error")
                        # Credentials are now cached by sudo for future use
                    except Exception as e:
                        self.notify(f"Failed to cache sudo credentials: {e}", severity="error")
                # Continue with initialization regardless
                self.finish_initialization()

            self.push_screen(SudoPasswordDialog(self), on_password)
            return  # Will call finish_initialization after dialog

        except Exception:
            # If there's an error, just continue
            self.finish_initialization()

    def finish_initialization(self) -> None:
        """Complete initialization after sudo password dialog"""
        # Check if initial setup is needed
        needs_setup = (
            not Config.SERVICES_DIR.exists() or
            not UserManager.group_exists() or
            not Config.CONFIG_DIR.exists()
        )

        if needs_setup:
            self.push_screen(InitialSetupDialog(self))
        else:
            # Check and ensure user is in group
            self.ensure_group_membership()
            # Initialize all tables
            self.initialize_all_tables()

    def initialize_all_tables(self) -> None:
        """Initialize all data tables"""
        self.refresh_system_table()
        self.refresh_services_table()
        # Load users table in background
        self.run_worker(self.refresh_users_table)
        self.refresh_host_table()

    def ensure_group_membership(self) -> None:
        """Check if current user is in infra-users group"""
        if not UserManager.group_exists():
            self.notify(f"Group '{UserManager.GROUP_NAME}' does not exist. Please run install.sh", severity="error")
            return

        if UserManager.is_user_in_group():
            return

        # User not in group - show notification
        current_user = os.environ.get("USER", os.environ.get("USERNAME", ""))
        self.notify(
            f"User '{current_user}' not in '{UserManager.GROUP_NAME}' group. "
            f"Use 'sudo usermod -aG {UserManager.GROUP_NAME} {current_user}' to add",
            severity="warning",
            timeout=10
        )

    def refresh_services_table(self) -> None:
        """Refresh the services status table"""
        try:
            table = self.query_one("#services-table", DataTable)
            table.clear(columns=True)
            table.add_column("Service", width=20)
            table.add_column("Status", width=15)
            table.add_column("Uptime", width=20)
            table.add_column("Ports", width=30)

            services = Config.get_managed_services()
            for service in services:
                status = DockerManager.get_container_status(service)

                if status["status"] == "running":
                    status_str = "[green]Running[/]"
                elif status["status"] == "stopped":
                    status_str = "[yellow]Stopped[/]"
                else:
                    status_str = "[red]Not created[/]"

                uptime = status["uptime"] or "-"
                ports = ", ".join(status["ports"][:3]) if status["ports"] else "-"

                table.add_row(service, status_str, uptime, ports)
        except:
            pass  # Table may not be visible yet

    def refresh_system_table(self) -> None:
        """Refresh the system information table"""
        try:
            table = self.query_one("#system-table", DataTable)
            table.clear(columns=True)
            table.add_column("Property", width=20)
            table.add_column("Value", width=60)

            sysinfo = HostManager.get_system_info()

            # System info
            table.add_row("[bold]Operating System[/]", sysinfo.get("os", "Unknown"))
            table.add_row("[bold]Kernel[/]", sysinfo.get("kernel", "Unknown"))
            table.add_row("[bold]Architecture[/]", sysinfo.get("arch", "Unknown"))
            table.add_row("[bold]Hostname[/]", sysinfo.get("hostname", "Unknown"))
            table.add_row("[bold]Uptime[/]", sysinfo.get("uptime", "Unknown"))

            # Hardware info
            table.add_row("[bold]CPU[/]", sysinfo.get("cpu", "Unknown"))
            table.add_row("[bold]Memory[/]", sysinfo.get("memory", "Unknown"))
            table.add_row("[bold]Disk (/)[/]", sysinfo.get("disk", "Unknown"))
            table.add_row("[bold]Load Average[/]", sysinfo.get("load", "Unknown"))

            # User info
            table.add_row("[bold]Current User[/]", sysinfo.get("user", "Unknown"))

        except:
            pass  # Table may not be visible yet

    async def refresh_users_table(self) -> None:
        """Refresh the users list"""
        try:
            users_list = self.query_one("#users-list", ScrollableContainer)
            # Clear existing children
            await users_list.remove_children()

            # Get group members
            group_members = set(UserManager.get_group_members())

            # Get all system users
            all_users = UserManager.get_all_users()

            for user in sorted(all_users):
                in_group = user in group_members
                in_docker = UserManager.is_in_docker_group(user)
                is_sudoer = UserManager.is_sudoer(user)
                has_passwordless = UserManager.has_passwordless_sudo(user) if is_sudoer else False

                # Check password status (locked or not)
                try:
                    result = subprocess.run(
                        ["sudo", "-n", "passwd", "-S", user],
                        capture_output=True,
                        text=True
                    )
                    parts = result.stdout.split()
                    password_locked = len(parts) >= 2 and parts[1] == "L"
                except Exception:
                    password_locked = False

                # Infra group action button
                if in_group:
                    group_btn = Button("Remove", id=f"remove-{user}", variant="error", classes="col-group-btn")
                else:
                    group_btn = Button("Add", id=f"add-{user}", variant="success", classes="col-group-btn")

                # Docker group action button
                if in_docker:
                    docker_btn = Button("Remove", id=f"docker-remove-{user}", variant="error", classes="col-docker-btn")
                else:
                    docker_btn = Button("Add", id=f"docker-add-{user}", variant="success", classes="col-docker-btn")

                # Add to sudoers button
                if is_sudoer:
                    add_sudo_btn = Button("Yes", id=f"add-sudo-{user}", variant="default", disabled=True, classes="col-add-sudo-btn")
                else:
                    add_sudo_btn = Button("Add", id=f"add-sudo-{user}", variant="success", classes="col-add-sudo-btn")

                # Passwordless sudo action button
                if is_sudoer:
                    if has_passwordless:
                        nopass_btn = Button("Disable", id=f"disable-nopass-{user}", variant="error", classes="col-sudo-btn")
                    else:
                        nopass_btn = Button("Enable", id=f"enable-nopass-{user}", variant="success", classes="col-sudo-btn")
                else:
                    nopass_btn = Label("—", id=f"nopass-{user}", classes="col-sudo-placeholder")

                # Password button - Lock/Unlock or Set password
                if password_locked:
                    passwd_btn = Button("Unlock", id=f"unlock-passwd-{user}", variant="success", classes="col-passwd-btn")
                else:
                    passwd_btn = Button("Lock", id=f"lock-passwd-{user}", variant="warning", classes="col-passwd-btn")

                # Delete button - only enabled if user can be deleted
                can_delete, reason = UserManager.can_delete_user(user)
                if can_delete:
                    delete_btn = Button("Delete", id=f"delete-user-{user}", variant="error", classes="col-delete-btn")
                else:
                    delete_btn = Button(reason, id=f"delete-user-{user}", variant="default", disabled=True, classes="col-delete-btn")

                # Create a horizontal row for each user
                row = Horizontal(
                    Label(user, classes="col-username"),
                    group_btn,
                    docker_btn,
                    add_sudo_btn,
                    nopass_btn,
                    passwd_btn,
                    delete_btn,
                )

                await users_list.mount(row)

            self.notify(f"Found {len(all_users)} user(s), {len(group_members)} in group", severity="information")
        except Exception as e:
            self.notify(f"Error loading users: {e}", severity="error")

    def refresh_host_table(self) -> None:
        """Refresh host software table"""
        try:
            host_tab = self.query_one(HostTab)
            host_tab.refresh_software()
        except:
            pass

    def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
        """Handle tab switching"""
        self.query_one(ContentSwitcher).current = event.tab.id.replace("-tab", "") + "-content"

        # Load users when switching to users tab
        if event.tab.id == "users-tab":
            self.run_worker(self.refresh_users_table)

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses"""
        button_id = event.button.id

        # Handle user add/remove buttons (format: add-username or remove-username)
        if button_id and button_id.startswith("add-") and button_id != "add-user-create":
            username = button_id[4:]  # Remove "add-" prefix
            group_members = set(UserManager.get_group_members())
            if username in group_members:
                self.notify(f"User '{username}' is already in the group", severity="warning")
                return

            def do_add():
                success = UserManager.add_user_to_group(username)
                if success:
                    self.notify(f"User '{username}' added to group", severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(f"Failed to add user '{username}'", severity="error")

            self.push_screen(ConfirmDialog(
                f"Add user **{username}** to '{UserManager.GROUP_NAME}' group?",
                on_confirm=do_add
            ))
            return

        elif button_id and button_id.startswith("remove-"):
            username = button_id[7:]  # Remove "remove-" prefix
            group_members = set(UserManager.get_group_members())
            if username not in group_members:
                self.notify(f"User '{username}' is not in the group", severity="warning")
                return

            def do_remove():
                success = UserManager.remove_user_from_group(username)
                if success:
                    self.notify(f"User '{username}' removed from group", severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(f"Failed to remove user '{username}'", severity="error")

            self.push_screen(ConfirmDialog(
                f"Remove user **{username}** from '{UserManager.GROUP_NAME}' group?",
                on_confirm=do_remove
            ))
            return

        # Handle docker group add/remove buttons
        elif button_id and button_id.startswith("docker-add-"):
            username = button_id[len("docker-add-"):]

            def do_add_docker():
                result = UserManager.add_to_docker_group(username)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(result["message"], severity="error")

            self.push_screen(ConfirmDialog(
                f"Add user **{username}** to 'docker' group?\n\n"
                f"This allows running Docker commands without sudo.",
                on_confirm=do_add_docker
            ))
            return

        elif button_id and button_id.startswith("docker-remove-"):
            username = button_id[len("docker-remove-"):]

            def do_remove_docker():
                result = UserManager.remove_from_docker_group(username)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(result["message"], severity="error")

            self.push_screen(ConfirmDialog(
                f"Remove user **{username}** from 'docker' group?",
                on_confirm=do_remove_docker
            ))
            return

        # Handle existing buttons
        if button_id == "ssh-disable-password":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.disable_password_auth()

        elif button_id == "ssh-disable-root":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.disable_root_login()

        elif button_id == "ssh-test":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.test_ssh_for_user()

        elif button_id == "ssh-lock-password":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.lock_user_password()

        elif button_id == "ssh-disable-user":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.disable_user_ssh()

        elif button_id == "ssh-setup-keys":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.setup_ssh_keys()

        elif button_id == "create-user":
            # First select user type, then enter username
            self.push_screen(SelectUserTypeDialog(self))

        # External registries buttons
        elif button_id == "reg-add":
            self.add_external_registry()

        elif button_id == "reg-sync":
            self.sync_external_registry()

        elif button_id == "reg-remove":
            self.remove_external_registry()

        elif button_id and button_id.startswith("enable-nopass-"):
            username = button_id[len("enable-nopass-"):]
            def do_enable():
                result = UserManager.set_passwordless_sudo(username, True)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(result["message"], severity="error")

            self.push_screen(ConfirmDialog(
                f"Enable passwordless sudo for **{username}**?\n\n"
                f"This user will be able to run sudo commands without entering a password.",
                on_confirm=do_enable
            ))
            return

        elif button_id and button_id.startswith("disable-nopass-"):
            username = button_id[len("disable-nopass-"):]
            import getpass
            current_user = getpass.getuser()

            def do_disable():
                result = UserManager.set_passwordless_sudo(username, False)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)

                    # If disabling for current user, exit the app
                    if username == current_user:
                        self.notify("Passwordless sudo disabled for your account. Restarting app...", severity="warning")
                        self.exit()
                else:
                    self.notify(result["message"], severity="error")

            message = f"Disable passwordless sudo for **{username}**?"
            if username == current_user:
                message += "\n\n**WARNING**: You are disabling passwordless sudo for your own account!\n\nThe app will exit and you will need to enter your password on restart."

            self.push_screen(ConfirmDialog(
                message,
                on_confirm=do_disable
            ))
            return

        elif button_id and button_id.startswith("add-sudo-"):
            username = button_id[len("add-sudo-"):]

            def do_add_sudo():
                result = UserManager.add_to_sudoers(username)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(result["message"], severity="error")

            self.push_screen(ConfirmDialog(
                f"Add **{username}** to sudoers group?\n\nThis will allow the user to run commands as root.",
                on_confirm=do_add_sudo
            ))
            return

        elif button_id and button_id.startswith("lock-passwd-"):
            username = button_id[len("lock-passwd-"):]

            def do_lock():
                try:
                    subprocess.run(["sudo", "passwd", "-l", username], check=True, capture_output=True)
                    self.notify(f"Password locked for {username} (account-wide)", severity="information")
                    self.run_worker(self.refresh_users_table)
                except subprocess.CalledProcessError as e:
                    self.notify(f"Failed to lock password: {e}", severity="error")

            self.push_screen(ConfirmDialog(
                f"**Lock password for {username}?**\n\n"
                f"This will **account-wide** lock the password for:\n"
                f"* SSH\n"
                f"* RDP (Remote Desktop)\n"
                f"* Console login\n"
                f"* All other services\n\n"
                f"The user will NOT be able to log in anywhere with a password.\n"
                f"SSH key authentication will still work if configured.",
                on_confirm=do_lock
            ))
            return

        elif button_id and button_id.startswith("unlock-passwd-"):
            username = button_id[len("unlock-passwd-"):]

            def do_unlock():
                try:
                    subprocess.run(["sudo", "passwd", "-u", username], check=True, capture_output=True)
                    self.notify(f"Password unlocked for {username}", severity="information")
                    self.run_worker(self.refresh_users_table)
                except subprocess.CalledProcessError as e:
                    self.notify(f"Failed to unlock password: {e}", severity="error")

            self.push_screen(ConfirmDialog(
                f"**Unlock password for {username}?**\n\n"
                f"This will re-enable password login for all services.",
                on_confirm=do_unlock
            ))
            return

        elif button_id and button_id.startswith("delete-user-"):
            username = button_id[len("delete-user-"):]

            def do_delete():
                result = UserManager.delete_user(username)
                if result["success"]:
                    self.notify(result["message"], severity="information")
                    self.run_worker(self.refresh_users_table)
                else:
                    self.notify(result["message"], severity="error")

            self.push_screen(ConfirmDialog(
                f"Delete user **{username}**?\n\nThis action cannot be undone.",
                on_confirm=do_delete
            ))
            return

    def action_refresh(self) -> None:
        """Refresh current tab"""
        tabs = self.query_one(Tabs)
        active_tab = tabs.active

        if active_tab == "system-tab":
            self.refresh_system_table()
            self.notify("System info refreshed", severity="information")
        elif active_tab == "services-tab":
            self.refresh_services_table()
            self.notify("Docker services refreshed", severity="information")
        elif active_tab == "registry-tab":
            registry_tab = self.query_one("#registry-content", RegistryTab)
            registry_tab.refresh_registry()
            self.notify("Registry refreshed", severity="information")
        elif active_tab == "users-tab":
            self.run_worker(self.refresh_users_table)
            self.notify("Users refreshed", severity="information")
        elif active_tab == "host-tab":
            self.refresh_host_table()
            self.notify("Host info refreshed", severity="information")
        elif active_tab == "ssh-tab":
            ssh_tab = self.query_one("#ssh-content", SSHTab)
            ssh_tab.refresh_ssh_config()
            ssh_tab.refresh_ssh_users()
            self.notify("SSH status refreshed", severity="information")
        elif active_tab == "registries-tab":
            registries_tab = self.query_one("#registries-content", RegistriesTab)
            registries_tab.refresh_registries()
            self.notify("Registries refreshed", severity="information")

    def action_switch_tab(self, tab_name: str) -> None:
        """Switch to a specific tab"""
        tabs = self.query_one(Tabs)
        tab_id = f"{tab_name}-tab"
        # Set active tab by ID string
        tabs.active = tab_id

    def test_cloudflare(self) -> None:
        """Test Cloudflare connection"""
        tokens = Config.get_cloudflare_tokens()

        if not tokens:
            self.notify("No tokens configured. Click 'Add Token' to create one", severity="error")
            return

        # Use the first available token
        token_name = list(tokens.keys())[0]
        cf = CloudflareManager(token_name=token_name)

        result = cf.test_connection()
        if result["success"]:
            self.notify(f"Connection successful using token '{token_name}'", severity="information")
        else:
            self.notify("Cloudflare connection failed", severity="error")

    def add_external_registry(self) -> None:
        """Add a new external registry"""
        def on_dialog_result(result):
            if result:
                name = result["name"]
                url = result["url"]
                branch = result["branch"]

                self.notify(f"Adding registry '{name}'...", severity="information")

                def do_add():
                    add_result = RegistryManager.add_external_registry(name, url, branch)
                    if add_result["success"]:
                        self.call_from_thread(
                            self.notify, f"Registry '{name}' added successfully", severity="information"
                        )
                    else:
                        self.call_from_thread(
                            self.notify, f"Failed to add registry: {add_result['message']}", severity="error"
                        )
                    # Refresh the registries table
                    try:
                        registries_tab = self.query_one("#registries-content", RegistriesTab)
                        self.call_from_thread(registries_tab.refresh_registries)
                    except Exception:
                        pass

                self.run_worker(do_add, thread=True)

        self.push_screen(AddRegistryDialog(self), on_dialog_result)

    def sync_external_registry(self) -> None:
        """Sync the selected external registry"""
        try:
            registries_tab = self.query_one("#registries-content", RegistriesTab)
            name = registries_tab.selected_registry

            if not name:
                self.notify("No registry selected", severity="error")
                return

            self.notify(f"Syncing registry '{name}'...", severity="information")

            def do_sync():
                result = RegistryManager.sync_external_registry(name)
                if result["success"]:
                    self.call_from_thread(
                        self.notify, f"Registry '{name}' synced successfully", severity="information"
                    )
                else:
                    self.call_from_thread(
                        self.notify, f"Failed to sync: {result['message']}", severity="error"
                    )
                # Refresh the registries table
                try:
                    self.call_from_thread(registries_tab.refresh_registries)
                except Exception:
                    pass

            self.run_worker(do_sync, thread=True)

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

    def remove_external_registry(self) -> None:
        """Remove the selected external registry"""
        try:
            registries_tab = self.query_one("#registries-content", RegistriesTab)
            name = registries_tab.selected_registry

            if not name:
                self.notify("No registry selected", severity="error")
                return

            def do_remove():
                result = RegistryManager.remove_external_registry(name)
                if result["success"]:
                    self.notify(f"Registry '{name}' removed", severity="information")
                else:
                    self.notify(f"Failed to remove: {result['message']}", severity="error")
                registries_tab.refresh_registries()

            self.push_screen(ConfirmDialog(
                f"Remove external registry **{name}**?\n\nThis will delete the local copy of the registry.",
                on_confirm=do_remove
            ))

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


def main():
    """Main entry point for TUI"""
    app = InfraTUI()
    app.run()


if __name__ == "__main__":
    main()
