"""
Interactive menu system for Claux CLI.

Provides a rich, user-friendly terminal interface.
"""

import sys
import os
import typer
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.layout import Layout
from rich.text import Text
from rich.align import Align

from claux import __version__
from claux.i18n import t, get_language
from claux.core.user_config import get_config

# Fix Windows console encoding
if os.name == 'nt':
    try:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        kernel32.SetConsoleOutputCP(65001)  # UTF-8
    except Exception:
        pass

app = typer.Typer(help="Interactive mode")
console = Console(force_terminal=True, legacy_windows=False)


def get_system_info():
    """Get system status information."""
    try:
        from claux.core.mcp import get_active_config
        from claux.core.profiles import get_active_profile

        mcp_config = get_active_config()
        profile = get_active_profile()
        py_version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"

        return {
            "python": py_version,
            "mcp": mcp_config or "none",
            "profile": profile or "none",
            "language": get_language(),
        }
    except Exception:
        return {
            "python": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
            "mcp": "none",
            "profile": "none",
            "language": get_language(),
        }


def show_banner():
    """Display welcome banner with system info."""
    # Create gradient title
    title = Text()
    title.append("🎼 ", style="bold cyan")
    title.append("C", style="bold cyan")
    title.append("l", style="bold blue")
    title.append("a", style="bold magenta")
    title.append("u", style="bold blue")
    title.append("x", style="bold cyan")
    title.append(f" v{__version__}", style="bold white")

    # Subtitle
    subtitle = Text("Token-Efficient AI Automation", style="dim italic")

    # Get system info
    info = get_system_info()

    # Create info bar
    info_text = Text()
    info_text.append("┃ ", style="dim cyan")
    info_text.append("🐍 ", style="")
    info_text.append(f"Python {info['python']}", style="dim")
    info_text.append(" * ", style="dim")
    info_text.append("🔌 ", style="")
    info_text.append(f"MCP: {info['mcp']}", style="dim green" if info['mcp'] != "none" else "dim yellow")
    info_text.append(" * ", style="dim")
    info_text.append("🤖 ", style="")
    info_text.append(f"Profile: {info['profile']}", style="dim blue" if info['profile'] != "none" else "dim yellow")
    info_text.append(" * ", style="dim")
    info_text.append("🌍 ", style="")
    info_text.append(info['language'].upper(), style="dim magenta")
    info_text.append(" ┃", style="dim cyan")

    # Create banner with panel
    banner_content = Text()
    banner_content.append("\n")
    banner_content.append(title.plain.center(80))
    banner_content.append("\n")
    banner_content.append(subtitle.plain.center(80), style="dim italic")
    banner_content.append("\n\n")

    # Info bar
    info_line = f"🐍 Python {info['python']}  *  🔌 MCP: {info['mcp']}  *  🤖 Profile: {info['profile']}  *  🌍 {info['language'].upper()}"

    banner_panel = Panel(
        f"[bold cyan]🎼 Claux[/bold cyan] [bold white]v{__version__}[/bold white]\n"
        f"[dim italic]Token-Efficient AI Automation[/dim italic]\n\n"
        f"[dim]{info_line}[/dim]",
        border_style="bold cyan",
        padding=(1, 2),
    )

    console.print()
    console.print(banner_panel)
    console.print()

    # Navigation hint
    hint = Panel(
        "[dim italic]↑↓ Navigate  *  ↵ Enter  *  Ctrl+C Exit[/dim italic]",
        border_style="dim",
        padding=(0, 1),
    )
    console.print(hint)
    console.print()


def show_breadcrumbs(path: str):
    """Show navigation breadcrumbs."""
    breadcrumb = Text()
    breadcrumb.append("┌─ ", style="dim cyan")
    breadcrumb.append("📍 ", style="")

    parts = path.split(" > ")
    for i, part in enumerate(parts):
        if i > 0:
            breadcrumb.append(" -> ", style="dim cyan")
        breadcrumb.append(part, style="bold cyan" if i == len(parts) - 1 else "dim")

    console.print(breadcrumb)
    console.print()


def main_menu():
    """Show main interactive menu."""
    show_banner()
    show_breadcrumbs("Main Menu")

    config = get_config()

    # Group choices by category for better organization
    choices = [
        # Setup & Quick Start
        Choice(value="wizard", name="🧙  Setup Wizard          │ Auto-configure projects"),
        "separator",
        # Configuration
        Choice(value="mcp", name="🔌  MCP Configuration     │ Manage MCP servers"),
        Choice(value="agents", name="🤖  Agent Profiles        │ Configure AI agents"),
        Choice(value="config", name="⚙️   Settings              │ Manage configuration"),
        Choice(value="lang", name="🌍  Language              │ Change interface language"),
        "separator",
        # Tools & Utilities
        Choice(value="bookmarks", name="📚  Project Bookmarks    │ Quick project access"),
        Choice(value="doctor", name="🩺  System Doctor         │ Diagnose issues"),
        Choice(value="history", name="📜  Command History      │ View past commands"),
        "separator",
        # Help & Exit
        Choice(value="help", name="❓  Help & Docs          │ View documentation"),
        Choice(value="exit", name="🚪  Exit                 │ Close Claux"),
    ]

    try:
        action = inquirer.select(
            message="* What would you like to do?",
            choices=choices,
            default="wizard",
            pointer=">",
        ).execute()
    except Exception as e:
        # Fallback for Cygwin and other incompatible terminals
        console.print("[yellow]!️  Interactive mode not supported in this terminal.[/yellow]")
        console.print("[dim]Try running in Windows CMD, PowerShell, or Windows Terminal.[/dim]\n")
        console.print("Available commands:")
        console.print("  claux wizard    - Run setup wizard")
        console.print("  claux mcp       - Manage MCP configurations")
        console.print("  claux agents    - Manage agent profiles")
        console.print("  claux lang      - Change language")
        console.print("  claux --help    - Show all commands\n")
        return "exit"

    return action


def mcp_menu():
    """MCP configuration submenu."""
    from claux.core.mcp import list_configs, get_active_config

    console.clear()
    show_breadcrumbs("Main Menu > MCP Configuration")

    configs = list_configs()
    current = get_active_config()

    # Create styled table
    table = Table(
        title="🔌 MCP Configurations",
        title_style="bold cyan",
        border_style="dim cyan",
        show_header=True,
        header_style="bold white",
    )
    table.add_column("Name", style="cyan", no_wrap=True)
    table.add_column("Status", style="green", justify="center")
    table.add_column("Token Budget", style="yellow", justify="right")
    table.add_column("Description", style="dim")

    config_details = {
        "base": ("~600", "Essential servers only (context7, sequential-thinking)"),
        "full": ("~5000", "All servers (supabase, playwright, n8n, shadcn)"),
    }

    for config_name in configs:
        status = "● Active" if config_name == current else "[ ] Inactive"
        tokens, desc = config_details.get(config_name, ("?", "Custom configuration"))
        table.add_row(
            config_name,
            status,
            tokens,
            desc,
        )

    console.print(table)
    console.print()

    choices = []
    for c in configs:
        indicator = "[*] " if c == current else "  "
        choices.append(Choice(value=c, name=f"{indicator}{c.upper()}"))

    choices.append("separator")
    choices.append(Choice(value="back", name="< Back to Main Menu"))

    selection = inquirer.select(
        message="* Select MCP configuration:",
        choices=choices,
        default=current,
        pointer=">",
    ).execute()

    if selection == "back":
        return

    # Switch MCP config
    from claux.core.mcp import switch_config
    switch_config(selection)

    # Success message with panel
    success_panel = Panel(
        f"[green][*][/green] Successfully switched to [bold cyan]{selection}[/bold cyan] configuration\n\n"
        "[yellow]![/yellow]  Remember to restart Claude Code for changes to take effect!",
        title="Configuration Updated",
        border_style="green",
    )
    console.print()
    console.print(success_panel)
    console.print()

    inquirer.confirm(
        message="Press Enter to continue...",
        default=True,
    ).execute()


def agent_profiles_menu():
    """Agent profiles submenu."""
    from claux.core.profiles import list_profiles, get_active_profile

    console.clear()
    show_breadcrumbs("Main Menu > Agent Profiles")

    profiles = list_profiles()
    current = get_active_profile()

    # Create styled table
    table = Table(
        title="🤖 Agent Profiles",
        title_style="bold cyan",
        border_style="dim cyan",
        show_header=True,
        header_style="bold white",
    )
    table.add_column("Profile", style="cyan", no_wrap=True)
    table.add_column("Status", style="green", justify="center")
    table.add_column("Agents", style="blue", justify="right")
    table.add_column("Token Savings", style="yellow", justify="right")
    table.add_column("Description", style="dim")

    profile_info = {
        "base": ("8", "82%", "Minimal set for basic operations"),
        "nextjs-full": ("28", "22%", "Full Next.js development stack"),
        "health-all": ("15", "56%", "All health workflow agents"),
        "development": ("12", "67%", "General development profile"),
    }

    for profile in profiles:
        status = "● Active" if profile == current else "[ ] Inactive"
        agents, savings, desc = profile_info.get(profile, ("?", "?", "Custom profile"))
        table.add_row(
            profile,
            status,
            agents,
            savings,
            desc,
        )

    console.print(table)
    console.print()

    choices = []
    for p in profiles:
        indicator = "[*] " if p == current else "  "
        choices.append(Choice(value=p, name=f"{indicator}{p}"))

    choices.append("separator")
    choices.append(Choice(value="back", name="< Back to Main Menu"))

    selection = inquirer.select(
        message="* Select agent profile:",
        choices=choices,
        default=current,
        pointer=">",
    ).execute()

    if selection == "back":
        return

    # Activate profile
    from claux.core.profiles import activate_profile
    activate_profile(selection)

    # Success message with panel
    profile_agents, profile_savings, _ = profile_info.get(selection, ("?", "?", ""))
    success_panel = Panel(
        f"[green][*][/green] Successfully activated profile: [bold cyan]{selection}[/bold cyan]\n\n"
        f"[dim]Agents loaded:[/dim] [blue]{profile_agents}[/blue]\n"
        f"[dim]Token savings:[/dim] [yellow]{profile_savings}[/yellow]\n\n"
        "[yellow]![/yellow]  Remember to restart Claude Code for changes to take effect!",
        title="Profile Activated",
        border_style="green",
    )
    console.print()
    console.print(success_panel)
    console.print()

    inquirer.confirm(
        message="Press Enter to continue...",
        default=True,
    ).execute()


def language_menu():
    """Language settings submenu."""
    from claux.i18n import get_available_languages, set_language, get_language

    console.clear()
    show_breadcrumbs("Main Menu > Language Settings")

    langs = get_available_languages()
    current = get_language()

    lang_names = {
        "en": "English",
        "ru": "Russian",
    }

    # Create info panel
    info_panel = Panel(
        "[dim]Select your preferred interface language.[/dim]\n"
        "[dim]This affects menus, messages, and prompts.[/dim]",
        title="🌍 Language Settings",
        border_style="cyan",
    )
    console.print(info_panel)
    console.print()

    choices = []
    for lang in langs:
        indicator = "[*] " if lang == current else "  "
        choices.append(Choice(value=lang, name=f"{indicator}{lang_names.get(lang, lang)}"))

    choices.append("separator")
    choices.append(Choice(value="back", name="< Back to Main Menu"))

    selection = inquirer.select(
        message="* Select language:",
        choices=choices,
        default=current,
        pointer=">",
    ).execute()

    if selection == "back":
        return

    set_language(selection)

    # Success message
    success_panel = Panel(
        f"[green][*][/green] Language changed to: [bold cyan]{lang_names.get(selection, selection)}[/bold cyan]\n\n"
        f"[yellow]💡 Tip:[/yellow] Set [bold]CLAUX_LANG={selection}[/bold] environment variable for permanent change",
        title="Language Updated",
        border_style="green",
    )
    console.print()
    console.print(success_panel)
    console.print()

    inquirer.confirm(
        message="Press Enter to continue...",
        default=True,
    ).execute()


def config_menu():
    """Configuration menu."""
    config = get_config()

    console.clear()
    show_breadcrumbs("Main Menu > Settings")

    # Info panel
    info_panel = Panel(
        "[dim]Manage Claux configuration and settings.[/dim]\n"
        "[dim]View, edit, or reset your configuration.[/dim]",
        title="⚙️  Configuration Manager",
        border_style="cyan",
    )
    console.print(info_panel)
    console.print()

    choices = [
        Choice(value="view", name="👁️   View Configuration    │ Display current settings"),
        Choice(value="edit", name="✏️   Edit Settings         │ Modify configuration"),
        Choice(value="reset", name="🔄  Reset to Defaults    │ Restore factory settings"),
        "separator",
        Choice(value="back", name="< Back to Main Menu"),
    ]

    selection = inquirer.select(
        message="* What would you like to do?",
        choices=choices,
        pointer=">",
    ).execute()

    if selection == "back":
        return
    elif selection == "view":
        import yaml
        console.print()
        config_panel = Panel(
            yaml.dump(config.load(), default_flow_style=False),
            title="📋 Current Configuration",
            border_style="cyan",
        )
        console.print(config_panel)
    elif selection == "reset":
        confirm = inquirer.confirm(
            message="!️  Are you sure you want to reset all settings to defaults?",
            default=False,
        ).execute()
        if confirm:
            config.reset()
            success_panel = Panel(
                "[green][*][/green] All settings have been reset to factory defaults",
                title="Reset Complete",
                border_style="green",
            )
            console.print()
            console.print(success_panel)

    console.print()
    inquirer.confirm(
        message="Press Enter to continue...",
        default=True,
    ).execute()


@app.command()
def menu():
    """Launch interactive menu."""
    while True:
        action = main_menu()

        if action == "exit":
            console.print("\n[bold cyan]Goodbye! 👋[/bold cyan]\n")
            break
        elif action == "wizard":
            from claux.commands.wizard import wizard_setup
            wizard_setup()
        elif action == "mcp":
            mcp_menu()
        elif action == "agents":
            agent_profiles_menu()
        elif action == "lang":
            language_menu()
        elif action == "config":
            config_menu()
        elif action == "bookmarks":
            console.print("\n[yellow]Bookmarks feature coming soon![/yellow]\n")
            typer.pause()
        elif action == "doctor":
            console.print("\n[yellow]Doctor diagnostic coming soon![/yellow]\n")
            typer.pause()
        elif action == "history":
            console.print("\n[yellow]History feature coming soon![/yellow]\n")
            typer.pause()
        elif action == "help":
            console.print("\n[bold]Help:[/bold] Visit https://github.com/Gerrux/claux\n")
            typer.pause()


if __name__ == "__main__":
    app()
