"""
Settings Tab for web access and other configuration
"""

from textual.widgets import Static, Button, Label, Input
from textual.containers import Horizontal, Vertical
from textual.app import ComposeResult
from textual.screen import ModalScreen
from textual import work
from ..core.ttyd import TtydManager


class WebAccessConfigDialog(ModalScreen):
    """Dialog for configuring web access settings"""

    CSS = """
    #web-config-dialog {
        align: center middle;
        border: thick cyan;
        padding: 2;
        background: $surface;
        width: 60;
    }

    #web-config-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    #web-config-dialog Label {
        margin-top: 1;
    }

    #web-config-dialog Input {
        margin-bottom: 1;
    }

    #web-config-buttons {
        align: center middle;
        margin-top: 2;
    }

    #web-config-buttons Button {
        min-width: 12;
        margin: 0 2;
    }
    """

    def __init__(self):
        super().__init__()
        self.config = TtydManager.get_config()

    def compose(self) -> ComposeResult:
        yield Vertical(
            Label("Configure Web Access", id="web-config-title"),
            Label("Port:", id="port-label"),
            Input(
                placeholder="7681",
                value=str(self.config.get("port", 7681)),
                id="port-input"
            ),
            Label("Username:", id="username-label"),
            Input(
                placeholder="admin",
                value=self.config.get("username", ""),
                id="username-input"
            ),
            Label("Password:", id="password-label"),
            Input(
                placeholder="Enter password",
                password=True,
                id="password-input"
            ),
            Label("Confirm Password:", id="confirm-password-label"),
            Input(
                placeholder="Confirm password",
                password=True,
                id="confirm-password-input"
            ),
            Label("[dim]Password is required for security[/]", id="password-help"),
            Horizontal(
                Button("Save", id="web-config-save", variant="success"),
                Button("Cancel", id="web-config-cancel", variant="default"),
                id="web-config-buttons"
            ),
            id="web-config-dialog"
        )

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "web-config-save":
            port_str = self.query_one("#port-input", Input).value.strip()
            username = self.query_one("#username-input", Input).value.strip()
            password = self.query_one("#password-input", Input).value
            confirm_password = self.query_one("#confirm-password-input", Input).value

            # Validation
            if not port_str:
                self.app.notify("Port is required", severity="error")
                return

            try:
                port = int(port_str)
                if port < 1 or port > 65535:
                    raise ValueError("Port out of range")
            except ValueError:
                self.app.notify("Invalid port number (1-65535)", severity="error")
                return

            if not username:
                self.app.notify("Username is required", severity="error")
                return

            if not password:
                self.app.notify("Password is required", severity="error")
                return

            if password != confirm_password:
                self.app.notify("Passwords do not match", severity="error")
                return

            if len(password) < 4:
                self.app.notify("Password must be at least 4 characters", severity="error")
                return

            # Save configuration
            result = TtydManager.save_config_with_credential(port, username, password)
            if result["success"]:
                self.app.notify("Configuration saved", severity="information")
                self.dismiss(True)
            else:
                self.app.notify(f"Failed to save: {result['message']}", severity="error")
        else:
            self.dismiss(False)


class SettingsTab(Static):
    """Tab for settings including web access configuration"""

    def compose(self) -> ComposeResult:
        yield Label("Settings", id="settings-title")
        yield Label("Press **R** to refresh", id="settings-help")

        # Web Access section
        yield Label("", id="settings-spacer1")
        yield Label("Web Access (ttyd)", id="web-access-title", classes="section-title")
        yield Label("[dim]Access the TUI from a web browser with basic authentication[/]", id="web-access-desc")

        yield Vertical(
            Horizontal(
                Label("ttyd Status:", id="ttyd-status-label", classes="status-label"),
                Label("[dim]Checking...[/]", id="ttyd-installed-status"),
                id="ttyd-status-row"
            ),
            Horizontal(
                Label("Server IP:", id="ip-label", classes="status-label"),
                Label("[dim]Checking...[/]", id="server-ip"),
                id="ip-row"
            ),
            Horizontal(
                Label("Service:", id="service-status-label", classes="status-label"),
                Label("[dim]Checking...[/]", id="service-status"),
                id="service-status-row"
            ),
            Horizontal(
                Label("URL:", id="url-label", classes="status-label"),
                Label("[dim]Not configured[/]", id="access-url"),
                Button("Copy", id="copy-url", variant="default", disabled=True),
                id="url-row"
            ),
            Horizontal(
                Label("Credentials:", id="creds-label", classes="status-label"),
                Label("[dim]Not configured[/]", id="creds-status"),
                id="creds-row"
            ),
            id="web-access-status"
        )

        yield Horizontal(
            Button("Install ttyd", id="install-ttyd", variant="primary", disabled=True),
            Button("Configure", id="configure-web", variant="success"),
            Button("Start", id="start-web", variant="success", disabled=True),
            Button("Stop", id="stop-web", variant="error", disabled=True),
            Button("Enable on Boot", id="enable-boot", variant="default", disabled=True),
            id="web-access-buttons"
        )

    def on_mount(self) -> None:
        """Initialize when tab is mounted"""
        self.refresh_status()

    def refresh_status(self) -> None:
        """Refresh all status displays"""
        self.refresh_ttyd_status()
        self.refresh_ip_status()
        self.refresh_service_status()

    def refresh_ip_status(self) -> None:
        """Refresh server IP display"""
        try:
            ip_label = self.query_one("#server-ip", Label)
            public_ip = TtydManager.get_public_ip()
            local_ip = TtydManager.get_local_ip()

            if public_ip:
                ip_label.update(f"[cyan]{public_ip}[/] (public)")
            elif local_ip:
                ip_label.update(f"[yellow]{local_ip}[/] (local only)")
            else:
                ip_label.update("[red]Could not detect[/]")
        except Exception:
            pass

    def refresh_ttyd_status(self) -> None:
        """Refresh ttyd installation status"""
        try:
            installed_label = self.query_one("#ttyd-installed-status", Label)
            install_btn = self.query_one("#install-ttyd", Button)

            if TtydManager.is_installed():
                version = TtydManager.get_version() or "unknown"
                installed_label.update(f"[green]Installed[/] (v{version})")
                install_btn.disabled = True
            else:
                installed_label.update("[red]Not installed[/]")
                install_btn.disabled = False
        except Exception:
            pass

    def refresh_service_status(self) -> None:
        """Refresh service status and button states"""
        try:
            service_label = self.query_one("#service-status", Label)
            url_label = self.query_one("#access-url", Label)
            creds_label = self.query_one("#creds-status", Label)
            copy_btn = self.query_one("#copy-url", Button)
            start_btn = self.query_one("#start-web", Button)
            stop_btn = self.query_one("#stop-web", Button)
            enable_btn = self.query_one("#enable-boot", Button)

            config = TtydManager.get_config()
            status = TtydManager.get_service_status()

            # Check if configured
            has_config = bool(config.get("username")) and bool(config.get("password_hash"))

            if has_config:
                creds_label.update(f"[green]Configured[/] (user: {config.get('username')})")
            else:
                creds_label.update("[yellow]Not configured[/] - click Configure")

            # Service status
            if not TtydManager.is_installed():
                service_label.update("[dim]ttyd not installed[/]")
                url_label.update("[dim]N/A[/]")
                copy_btn.disabled = True
                start_btn.disabled = True
                stop_btn.disabled = True
                enable_btn.disabled = True
                return

            if not has_config:
                service_label.update("[dim]Not configured[/]")
                url_label.update("[dim]Configure first[/]")
                copy_btn.disabled = True
                start_btn.disabled = True
                stop_btn.disabled = True
                enable_btn.disabled = True
                return

            # Always show URL if configured
            url = TtydManager.get_access_url()
            copy_btn.disabled = False  # Enable copy when URL is available
            if status["running"]:
                service_label.update("[green]Running[/]")
                url_label.update(f"[cyan]{url}[/]")
                start_btn.disabled = True
                stop_btn.disabled = False
            else:
                service_label.update("[red]Stopped[/]")
                url_label.update(f"[dim]{url}[/] (not running)")
                start_btn.disabled = False
                stop_btn.disabled = True

            enable_btn.disabled = False
            if status["enabled"]:
                enable_btn.label = "Disable on Boot"
                enable_btn.variant = "warning"
            else:
                enable_btn.label = "Enable on Boot"
                enable_btn.variant = "default"

        except Exception:
            pass

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses"""
        if event.button.id == "install-ttyd":
            self.install_ttyd()
        elif event.button.id == "configure-web":
            self.app.push_screen(WebAccessConfigDialog(), self.on_config_saved)
        elif event.button.id == "copy-url":
            self.copy_url()
        elif event.button.id == "start-web":
            self.start_service()
        elif event.button.id == "stop-web":
            self.stop_service()
        elif event.button.id == "enable-boot":
            self.toggle_boot()

    def copy_url(self) -> None:
        """Copy the access URL to clipboard"""
        url = TtydManager.get_access_url()
        if url:
            # Use Textual's built-in clipboard support (uses OSC 52)
            self.app.copy_to_clipboard(url)
            self.notify("URL copied to clipboard", severity="information")

    def on_config_saved(self, result: bool) -> None:
        """Called when config dialog is dismissed"""
        if result:
            self.refresh_status()

    def install_ttyd(self) -> None:
        """Install ttyd"""
        self.notify("Installing ttyd...", severity="information")
        self._do_install_ttyd()

    @work(thread=True)
    def _do_install_ttyd(self) -> None:
        """Worker to install ttyd"""
        result = TtydManager.install()
        if result["success"]:
            self.app.call_from_thread(
                self.notify, "ttyd installed successfully", severity="information"
            )
        else:
            self.app.call_from_thread(
                self.notify, f"Failed to install: {result['message']}", severity="error"
            )
        self.app.call_from_thread(self.refresh_status)

    def start_service(self) -> None:
        """Start the web access service"""
        self.notify("Starting web access service...", severity="information")
        self._do_start_service()

    @work(thread=True)
    def _do_start_service(self) -> None:
        """Worker to start service"""
        result = TtydManager.start_service()
        if result["success"]:
            self.app.call_from_thread(
                self.notify, "Service started", severity="information"
            )
        else:
            self.app.call_from_thread(
                self.notify, f"Failed to start: {result['message']}", severity="error"
            )
        self.app.call_from_thread(self.refresh_status)

    def stop_service(self) -> None:
        """Stop the web access service"""
        self.notify("Stopping web access service...", severity="information")
        self._do_stop_service()

    @work(thread=True)
    def _do_stop_service(self) -> None:
        """Worker to stop service"""
        result = TtydManager.stop_service()
        if result["success"]:
            self.app.call_from_thread(
                self.notify, "Service stopped", severity="information"
            )
        else:
            self.app.call_from_thread(
                self.notify, f"Failed to stop: {result['message']}", severity="error"
            )
        self.app.call_from_thread(self.refresh_status)

    def toggle_boot(self) -> None:
        """Toggle enable/disable on boot"""
        status = TtydManager.get_service_status()
        enable = not status["enabled"]
        action = "Enabling" if enable else "Disabling"
        self.notify(f"{action} service on boot...", severity="information")
        self._do_toggle_boot(enable)

    @work(thread=True)
    def _do_toggle_boot(self, enable: bool) -> None:
        """Worker to toggle boot status"""
        result = TtydManager.enable_on_boot(enable)
        if result["success"]:
            self.app.call_from_thread(
                self.notify, result["message"], severity="information"
            )
        else:
            self.app.call_from_thread(
                self.notify, f"Failed: {result['message']}", severity="error"
            )
        self.app.call_from_thread(self.refresh_status)
