using HanaTui.Hana;
using Spectre.Console;

namespace HanaTui.Tui;

/// <summary>
/// The main operation menu. Returns the selected operation, or null to exit.
/// </summary>
public static class MainMenuScreen
{
    public enum Operation
    {
        Export,
        Import,
        ImportRename,
        Copy,
        Drop,
        RenameDb,
        Backup,
        ChangeKey,
        Quit,
    }

    public static Operation Run(HdbUserstoreKey? key, string keyName)
    {
        AnsiConsole.Clear();

        // Header with key info
        var rule = new Rule("[bold dodgerblue1]HANA Database Manager[/]")
            .RuleStyle(Style.Parse("dodgerblue1"));
        AnsiConsole.Write(rule);

        if (key is not null)
        {
            var conn = key.Host + ":" + key.Port +
                       (string.IsNullOrEmpty(key.Tenant) ? "" : "@" + key.Tenant) +
                       "  user=" + key.User;
            AnsiConsole.MarkupLine(
                $"  Key: [bold yellow]{Markup.Escape(key.Name)}[/]  [dim]{Markup.Escape(conn)}[/]");
        }
        else
        {
            AnsiConsole.MarkupLine($"  Key: [bold yellow]{Markup.Escape(keyName)}[/]");
        }

        AnsiConsole.WriteLine();

        var choices = new Dictionary<string, Operation>
        {
            ["1  Export Schema"]                   = Operation.Export,
            ["2  Import Schema"]                   = Operation.Import,
            ["3  Import & Rename Schema"]           = Operation.ImportRename,
            ["4  Copy Schema"]                      = Operation.Copy,
            ["5  Drop Schema"]                      = Operation.Drop,
            ["6  Rename Database (Company Name)"]   = Operation.RenameDb,
            ["7  Backup Tenant"]                    = Operation.Backup,
            ["----------------------------------"]   = Operation.Quit, // separator placeholder
            ["k  Change Key"]                       = Operation.ChangeKey,
            ["q  Quit"]                             = Operation.Quit,
        };

        // Build SelectionPrompt without the separator entry
        var prompt = new SelectionPrompt<string>()
            .Title("[bold]Select operation:[/]")
            .PageSize(12)
            .HighlightStyle(Style.Parse("bold dodgerblue1"));

        foreach (var key2 in choices.Keys)
        {
            if (key2.StartsWith("--")) continue;
            prompt.AddChoice(key2);
        }

        var selected = AnsiConsole.Prompt(prompt);
        return choices.TryGetValue(selected, out var op) ? op : Operation.Quit;
    }
}
