"""Presenter for external integration UI in CLI."""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from prompt_toolkit.application import Application
    from prompt_toolkit.key_binding.key_processor import KeyPressEvent

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text


class IntegrationPresenter:
    """Presenter for external integration UI in CLI."""

    def __init__(self) -> None:
        """Initialize the integration presenter."""
        self.console = Console()

    def show_integration_status(self, status: dict[str, Any]) -> None:
        """Display comprehensive integration status."""
        self.console.print("\n🔗 [bold blue]External Integration Status[/bold blue]\n")

        # Terminal Integrations
        terminals_table = Table(
            title="Terminal Integrations", show_header=True, header_style="bold magenta"
        )
        terminals_table.add_column("Tool", style="cyan")
        terminals_table.add_column("Status", style="green")
        terminals_table.add_column("Version", style="yellow")
        terminals_table.add_column("Features", style="blue")

        for _, tool_status in status["terminals"].items():
            status_icon = "✅" if tool_status["available"] else "❌"
            status_text = "Available" if tool_status["available"] else "Not Available"

            # Format features
            features = []
            for feature, supported in tool_status["features"].items():
                if supported:
                    features.append(f"✓ {feature.replace('_', ' ').title()}")
                else:
                    features.append(f"✗ {feature.replace('_', ' ').title()}")

            terminals_table.add_row(
                tool_status["name"],
                f"{status_icon} {status_text}",
                tool_status["version"],
                "\n".join(features),
            )

        self.console.print(terminals_table)

        # Editor Integrations
        editors_table = Table(
            title="Editor Integrations", show_header=True, header_style="bold magenta"
        )
        editors_table.add_column("Tool", style="cyan")
        editors_table.add_column("Status", style="green")
        editors_table.add_column("Version", style="yellow")
        editors_table.add_column("Features", style="blue")

        for _, tool_status in status["editors"].items():
            status_icon = "✅" if tool_status["available"] else "❌"
            status_text = "Available" if tool_status["available"] else "Not Available"

            # Format features
            features = []
            for feature, supported in tool_status["features"].items():
                if supported:
                    features.append(f"✓ {feature.replace('_', ' ').title()}")
                else:
                    features.append(f"✗ {feature.replace('_', ' ').title()}")

            editors_table.add_row(
                tool_status["name"],
                f"{status_icon} {status_text}",
                tool_status["version"],
                "\n".join(features),
            )

        self.console.print(editors_table)

    def show_available_integrations(
        self, terminals: list[dict[str, Any]], editors: list[dict[str, Any]]
    ) -> None:
        """Display available integrations in a clean format."""
        self.console.print("\n✨ [bold green]Available Integrations[/bold green]\n")

        if not terminals and not editors:
            self.console.print(
                Panel(
                    "[yellow]No external integrations are currently available.[/yellow]\n\n"
                    "To enable integrations, install one of the supported tools:\n"
                    "• iTerm2 for enhanced terminal features\n"
                    "• Cursor or VSCode for editor integration",
                    title="No Integrations",
                    border_style="yellow",
                )
            )
            return

        if terminals:
            terminals_text = Text()
            terminals_text.append("🖥️  Terminals:\n", style="bold blue")
            for terminal in terminals:
                terminals_text.append(
                    f"  • {terminal['name']} ({terminal['version']})\n", style="green"
                )

            self.console.print(Panel(terminals_text, border_style="blue"))

        if editors:
            editors_text = Text()
            editors_text.append("📝 Editors:\n", style="bold blue")
            for editor in editors:
                editors_text.append(f"  • {editor['name']} ({editor['version']})\n", style="green")

            self.console.print(Panel(editors_text, border_style="blue"))

    def show_integration_menu(self) -> str | None:
        """Show interactive integration menu and return choice."""
        # Check if we can use interactive mode
        if not sys.stdin.isatty() or not sys.stdout.isatty():
            return self._show_fallback_menu()

        try:
            # Try to use prompt_toolkit for a better experience
            from prompt_toolkit import Application
            from prompt_toolkit.formatted_text import HTML
            from prompt_toolkit.key_binding import KeyBindings
            from prompt_toolkit.layout import Layout, Window
            from prompt_toolkit.layout.controls import FormattedTextControl
            from prompt_toolkit.styles import Style

            # Menu options
            options = [
                ("status", "📊 Show Integration Status"),
                ("list", "📋 List Available Integrations"),
                ("test", "🧪 Test Integrations"),
                ("recommendations", "💡 Show Recommendations"),
                ("quit", "🚪 Back to Main Menu"),
            ]

            current_index = 0
            selected_action = None

            def get_formatted_text() -> list[Any]:
                """Generate formatted menu text."""
                result = []
                result.append(HTML("\n<bold><cyan>🔗 External Integrations Menu</cyan></bold>\n"))

                for i, (_, label) in enumerate(options):
                    if i == current_index:
                        result.append(HTML(f"<reverse>▶ {label}</reverse>\n"))
                    else:
                        result.append(HTML(f"  {label}\n"))

                result.append(HTML("\n<dim>↑/↓ Navigate • Enter: Select • Q: Quit</dim>"))
                return result

            kb = KeyBindings()

            @kb.add("up")
            @kb.add("k")
            def move_up(_event: KeyPressEvent) -> None:
                nonlocal current_index
                if current_index > 0:
                    current_index -= 1

            @kb.add("down")
            @kb.add("j")
            def move_down(_event: KeyPressEvent) -> None:
                nonlocal current_index
                if current_index < len(options) - 1:
                    current_index += 1

            @kb.add("enter")
            def select_item(event: KeyPressEvent) -> None:
                nonlocal selected_action
                selected_action = options[current_index][0]
                event.app.exit()

            @kb.add("q")
            @kb.add("escape")
            @kb.add("c-c")
            def quit_menu(event: KeyPressEvent) -> None:
                nonlocal selected_action
                selected_action = "quit"
                event.app.exit()

            # Clear screen
            print("\033[2J\033[H", end="", flush=True)

            window = Window(
                content=FormattedTextControl(
                    text=get_formatted_text,
                    focusable=True,
                ),
                height=len(options) + 5,
            )

            app: Application[None] = Application(
                layout=Layout(window),
                key_bindings=kb,
                full_screen=False,
                style=Style.from_dict(
                    {
                        "": "",
                    }
                ),
            )

            app.run()

            return selected_action

        except ImportError:
            # Fall back to simple text menu
            return self._show_fallback_menu()

    def _show_fallback_menu(self) -> str | None:
        """Fallback menu when prompt_toolkit is not available."""
        self.console.print("\n[bold cyan]🔗 External Integrations Menu[/bold cyan]\n")
        self.console.print("1. 📊 Show Integration Status")
        self.console.print("2. 📋 List Available Integrations")
        self.console.print("3. 🧪 Test Integrations")
        self.console.print("4. 💡 Show Recommendations")
        self.console.print("0. 🚪 Back to Main Menu")

        try:
            choice = input("\nSelect option: ").strip()
            actions = {"0": "quit", "1": "status", "2": "list", "3": "test", "4": "recommendations"}
            return actions.get(choice)
        except (KeyboardInterrupt, EOFError):
            return "quit"

        return None

    def show_integration_test_results(self, status: dict[str, Any]) -> None:
        """Show test results for integrations."""
        self.console.print("\n🧪 [bold blue]Integration Test Results[/bold blue]\n")

        # Create a summary table
        test_table = Table(title="Test Results", show_header=True, header_style="bold magenta")
        test_table.add_column("Tool", style="cyan")
        test_table.add_column("Type", style="blue")
        test_table.add_column("Status", style="green")
        test_table.add_column("Result", style="yellow")

        # Test terminal integrations
        for _, tool_status in status["terminals"].items():
            result = "PASS" if tool_status["available"] else "NOT AVAILABLE"
            result_color = "green" if tool_status["available"] else "red"
            status_icon = "✅" if tool_status["available"] else "❌"

            test_table.add_row(
                tool_status["name"],
                "Terminal",
                f"{status_icon}",
                f"[{result_color}]{result}[/{result_color}]",
            )

        # Test editor integrations
        for _, tool_status in status["editors"].items():
            result = "PASS" if tool_status["available"] else "NOT AVAILABLE"
            result_color = "green" if tool_status["available"] else "red"
            status_icon = "✅" if tool_status["available"] else "❌"

            test_table.add_row(
                tool_status["name"],
                "Editor",
                f"{status_icon}",
                f"[{result_color}]{result}[/{result_color}]",
            )

        self.console.print(test_table)

    def show_recommendations(self, editor: str | None, terminal: str | None) -> None:
        """Show integration recommendations."""
        self.console.print("\n💡 [bold blue]Integration Recommendations[/bold blue]\n")

        recommendations_text = Text()

        if editor:
            recommendations_text.append("📝 Recommended Editor: ", style="bold")
            recommendations_text.append(f"{editor.title()}\n", style="green")
        else:
            recommendations_text.append("📝 No editor integrations available\n", style="yellow")
            recommendations_text.append("   Consider installing Cursor or VSCode\n", style="dim")

        if terminal:
            recommendations_text.append("🖥️  Recommended Terminal: ", style="bold")
            recommendations_text.append(f"{terminal.title()}\n", style="green")
        else:
            recommendations_text.append("🖥️  No terminal integrations available\n", style="yellow")
            recommendations_text.append(
                "   Consider installing iTerm2 for enhanced features\n", style="dim"
            )

        self.console.print(
            Panel(recommendations_text, title="Recommendations", border_style="blue")
        )

    def show_integration_summary(self, counts: dict[str, int]) -> None:
        """Show a brief summary of available integrations."""
        summary_text = Text()
        summary_text.append("📊 Integration Summary\n\n", style="bold blue")
        summary_text.append(f"Terminals: {counts['terminals']}\n", style="green")
        summary_text.append(f"Editors: {counts['editors']}\n", style="green")
        summary_text.append(f"Total: {counts['total']}\n", style="bold green")

        self.console.print(Panel(summary_text, title="Integration Summary", border_style="green"))
