"""
Navigation and action operations for the hosts TUI application.

This module handles entry movement, toggling, file operations,
and other navigation-related functionality.
"""

from textual.widgets import DataTable


class NavigationHandler:
    """Handles all navigation and action operations for the hosts manager."""

    def __init__(self, app):
        """Initialize the navigation handler with reference to the main app."""
        self.app = app

    def toggle_entry(self) -> None:
        """Toggle the active state of the selected entry."""
        if not self.app.edit_mode:
            self.app.update_status(
                "❌ Cannot toggle entry: Application is in read-only mode. Press 'Ctrl+E' to enable edit mode."
            )
            return

        if not self.app.hosts_file.entries:
            self.app.update_status("No entries to toggle")
            return

        # Remember current entry for cursor position restoration
        current_entry = self.app.hosts_file.entries[self.app.selected_entry_index]

        # Use command-based method for undo/redo support
        result = self.app.manager.execute_toggle_command(
            self.app.hosts_file, self.app.selected_entry_index
        )
        if result.success:
            # Auto-save the changes immediately
            save_success, save_message = self.app.manager.save_hosts_file(
                self.app.hosts_file
            )
            if save_success:
                self.app.table_handler.populate_entries_table()
                # Restore cursor position to the same entry
                self.app.set_timer(
                    0.1,
                    lambda: self.app.table_handler.restore_cursor_position(
                        current_entry
                    ),
                )
                self.app.details_handler.update_entry_details()
                self.app.update_status(f"{result.message} - Changes saved automatically")
            else:
                self.app.update_status(f"Entry toggled but save failed: {save_message}")
        else:
            self.app.update_status(f"Error toggling entry: {result.message}")

    def move_entry_up(self) -> None:
        """Move the selected entry up in the list."""
        if not self.app.edit_mode:
            self.app.update_status(
                "❌ Cannot move entry: Application is in read-only mode. Press 'Ctrl+E' to enable edit mode."
            )
            return

        if not self.app.hosts_file.entries:
            self.app.update_status("No entries to move")
            return

        # Use command-based method for undo/redo support
        result = self.app.manager.execute_move_command(
            self.app.hosts_file, self.app.selected_entry_index, "up"
        )
        if result.success:
            # Auto-save the changes immediately
            save_success, save_message = self.app.manager.save_hosts_file(
                self.app.hosts_file
            )
            if save_success:
                # Update the selection index to follow the moved entry
                if self.app.selected_entry_index > 0:
                    self.app.selected_entry_index -= 1
                self.app.table_handler.populate_entries_table()
                # Update the DataTable cursor position to follow the moved entry
                table = self.app.query_one("#entries-table", DataTable)
                display_index = self.app.table_handler.actual_index_to_display_index(
                    self.app.selected_entry_index
                )
                if table.row_count > 0 and display_index < table.row_count:
                    table.move_cursor(row=display_index)
                self.app.details_handler.update_entry_details()
                self.app.update_status(f"{result.message} - Changes saved automatically")
            else:
                self.app.update_status(f"Entry moved but save failed: {save_message}")
        else:
            self.app.update_status(f"Error moving entry: {result.message}")

    def move_entry_down(self) -> None:
        """Move the selected entry down in the list."""
        if not self.app.edit_mode:
            self.app.update_status(
                "❌ Cannot move entry: Application is in read-only mode. Press 'Ctrl+E' to enable edit mode."
            )
            return

        if not self.app.hosts_file.entries:
            self.app.update_status("No entries to move")
            return

        # Use command-based method for undo/redo support
        result = self.app.manager.execute_move_command(
            self.app.hosts_file, self.app.selected_entry_index, "down"
        )
        if result.success:
            # Auto-save the changes immediately
            save_success, save_message = self.app.manager.save_hosts_file(
                self.app.hosts_file
            )
            if save_success:
                # Update the selection index to follow the moved entry
                if self.app.selected_entry_index < len(self.app.hosts_file.entries) - 1:
                    self.app.selected_entry_index += 1
                self.app.table_handler.populate_entries_table()
                # Update the DataTable cursor position to follow the moved entry
                table = self.app.query_one("#entries-table", DataTable)
                display_index = self.app.table_handler.actual_index_to_display_index(
                    self.app.selected_entry_index
                )
                if table.row_count > 0 and display_index < table.row_count:
                    table.move_cursor(row=display_index)
                self.app.details_handler.update_entry_details()
                self.app.update_status(f"{result.message} - Changes saved automatically")
            else:
                self.app.update_status(f"Entry moved but save failed: {save_message}")
        else:
            self.app.update_status(f"Error moving entry: {result.message}")

    def save_hosts_file(self) -> None:
        """Save the hosts file to disk."""
        if not self.app.edit_mode:
            self.app.update_status(
                "❌ Cannot save: Application is in read-only mode. No changes to save."
            )
            return

        success, message = self.app.manager.save_hosts_file(self.app.hosts_file)
        if success:
            self.app.update_status(message)
        else:
            self.app.update_status(f"Error saving file: {message}")

    def quit_application(self) -> None:
        """Quit the application with proper cleanup."""
        # If in entry edit mode, exit it first
        if self.app.entry_edit_mode:
            self.app.edit_handler.exit_edit_entry_with_confirmation()
            return  # Let the confirmation handle the exit

        # If in edit mode, exit it first
        if self.app.edit_mode:
            self.app.manager.exit_edit_mode()

        self.app.exit()
