"""
Details pane management for the hosts TUI application.

This module handles the display and updating of entry details
and edit forms in the right pane.
"""

from textual.widgets import Input, Checkbox


class DetailsHandler:
    """Handles all details pane operations for the hosts manager."""

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

    def update_entry_details(self) -> None:
        """Update the right pane with selected entry details."""
        if self.app.entry_edit_mode:
            self.update_edit_form()
        else:
            self.update_details_display()

    def update_details_display(self) -> None:
        """Update the details display using disabled Input widgets."""
        details_display = self.app.query_one("#entry-details-display")
        edit_form = self.app.query_one("#entry-edit-form")

        # Show details display, hide edit form
        details_display.remove_class("hidden")
        edit_form.add_class("hidden")

        # Get the input widgets
        ip_input = self.app.query_one("#details-ip-input", Input)
        hostname_input = self.app.query_one("#details-hostname-input", Input)
        comment_input = self.app.query_one("#details-comment-input", Input)
        active_checkbox = self.app.query_one("#details-active-checkbox", Checkbox)

        if not self.app.hosts_file.entries:
            # Show empty message
            ip_input.value = ""
            ip_input.placeholder = "No entries loaded"
            hostname_input.value = ""
            hostname_input.placeholder = "No entries loaded"
            comment_input.value = ""
            comment_input.placeholder = "No entries loaded"
            active_checkbox.value = False
            return

        # Get visible entries to check if we need to adjust selection
        visible_entries = self.app.table_handler.get_visible_entries()
        if not visible_entries:
            ip_input.value = ""
            ip_input.placeholder = "No visible entries"
            hostname_input.value = ""
            hostname_input.placeholder = "No visible entries"
            comment_input.value = ""
            comment_input.placeholder = "No visible entries"
            active_checkbox.value = False
            return

        # If default entries are hidden and selected_entry_index points to a hidden entry,
        # we need to find the corresponding visible entry
        show_defaults = self.app.config.should_show_default_entries()
        if not show_defaults:
            # Check if the currently selected entry is a default entry (hidden)
            if (
                self.app.selected_entry_index < len(self.app.hosts_file.entries)
                and self.app.hosts_file.entries[
                    self.app.selected_entry_index
                ].is_default_entry()
            ):
                # The selected entry is hidden, so we should show the first visible entry instead
                if visible_entries:
                    # Find the first visible entry in the hosts file
                    for i, entry in enumerate(self.app.hosts_file.entries):
                        if not entry.is_default_entry():
                            self.app.selected_entry_index = i
                            break

        if self.app.selected_entry_index >= len(self.app.hosts_file.entries):
            self.app.selected_entry_index = 0

        entry = self.app.hosts_file.entries[self.app.selected_entry_index]

        # Update the input widgets with entry data
        ip_input.value = entry.ip_address
        ip_input.placeholder = ""
        hostname_input.value = ", ".join(entry.hostnames)
        hostname_input.placeholder = ""
        comment_input.value = entry.comment or ""
        comment_input.placeholder = "No comment"
        active_checkbox.value = entry.is_active

        # For default entries, show warning in placeholder text
        if entry.is_default_entry():
            ip_input.placeholder = "⚠️  SYSTEM DEFAULT ENTRY - Cannot be modified"
            hostname_input.placeholder = "⚠️  SYSTEM DEFAULT ENTRY - Cannot be modified"
            comment_input.placeholder = "⚠️  SYSTEM DEFAULT ENTRY - Cannot be modified"

        # Update DNS information if present
        self._update_dns_information(entry)

    def update_edit_form(self) -> None:
        """Update the edit form with current entry values."""
        details_display = self.app.query_one("#entry-details-display")
        edit_form = self.app.query_one("#entry-edit-form")

        # Hide details display, show edit form
        details_display.add_class("hidden")
        edit_form.remove_class("hidden")

        if not self.app.hosts_file.entries or self.app.selected_entry_index >= len(
            self.app.hosts_file.entries
        ):
            return

        entry = self.app.hosts_file.entries[self.app.selected_entry_index]

        # Update form fields with current entry values
        ip_input = self.app.query_one("#ip-input", Input)
        hostname_input = self.app.query_one("#hostname-input", Input)
        comment_input = self.app.query_one("#comment-input", Input)
        active_checkbox = self.app.query_one("#active-checkbox", Checkbox)

        ip_input.value = entry.ip_address
        hostname_input.value = ", ".join(entry.hostnames)
        comment_input.value = entry.comment or ""
        active_checkbox.value = entry.is_active

        # Initialize radio button state and field visibility
        self.app.edit_handler.populate_edit_form_with_type_detection()

    def _update_dns_information(self, entry) -> None:
        """Update DNS information display for the selected entry."""
        try:
            # Get the three separate DNS input fields
            dns_name_input = self.app.query_one("#details-dns-name-input", Input)
            dns_status_input = self.app.query_one("#details-dns-status-input", Input)
            dns_resolved_input = self.app.query_one("#details-dns-resolved-input", Input)
            
            if not entry.has_dns_name():
                # Clear all DNS fields if no DNS information
                dns_name_input.value = ""
                dns_name_input.placeholder = "No DNS name"
                dns_status_input.value = ""
                dns_status_input.placeholder = "No DNS status"
                dns_resolved_input.value = ""
                dns_resolved_input.placeholder = "Not resolved yet"
                return

            # Update DNS Name field
            dns_name_input.value = entry.dns_name or ""
            dns_name_input.placeholder = "" if entry.dns_name else "No DNS name"

            # Update DNS Status field
            if entry.dns_resolution_status:
                status_text = {
                    "not_resolved": "Not resolved",
                    "resolving": "Resolving...",
                    "resolved": "Resolved",
                    "failed": "Resolution failed",
                    "match": "IP matches DNS",
                    "mismatch": "IP differs from DNS"
                }.get(entry.dns_resolution_status, entry.dns_resolution_status)
                
                # Add resolved IP to status if available
                if entry.resolved_ip and entry.dns_resolution_status in ["resolved", "match", "mismatch"]:
                    status_text += f" ({entry.resolved_ip})"
                
                dns_status_input.value = status_text
                dns_status_input.placeholder = ""
            else:
                dns_status_input.value = ""
                dns_status_input.placeholder = "No DNS status"

            # Update Last Resolved field
            if entry.last_resolved:
                time_str = entry.last_resolved.strftime("%H:%M:%S")
                date_str = entry.last_resolved.strftime("%Y-%m-%d")
                dns_resolved_input.value = f"{date_str} {time_str}"
                dns_resolved_input.placeholder = ""
            else:
                dns_resolved_input.value = ""
                dns_resolved_input.placeholder = "Not resolved yet"

        except Exception:
            # DNS widgets not present yet, silently ignore
            pass
