using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Net;
using PlotLine.Services;

namespace PlotLine.TagHelpers;

[HtmlTargetElement("help-icon", Attributes = "key")]
public sealed class HelpIconTagHelper(IHelpService help) : TagHelper
{
    public string Key { get; set; } = string.Empty;
    public string? Mode { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var article = help.GetByContextKey(Key);
        var isInline = string.Equals(Mode, "inline", StringComparison.OrdinalIgnoreCase);
        var micro = string.IsNullOrWhiteSpace(article?.Micro)
            ? "Help article not found."
            : article.Micro;
        var quickTitle = string.IsNullOrWhiteSpace(article?.QuickTitle)
            ? "Help unavailable"
            : article.QuickTitle;
        var quickSummary = string.IsNullOrWhiteSpace(article?.QuickSummary)
            ? "Help content has not yet been written for this feature."
            : article.QuickSummary;

        output.TagName = "span";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.SetAttribute("class", isInline
            ? "plotline-help-icon-wrapper plotline-help-icon-wrapper-inline"
            : "plotline-help-icon-wrapper");
        output.Attributes.SetAttribute("data-help-icon", "true");
        output.Attributes.SetAttribute("data-help-key", Key);
        output.Attributes.SetAttribute("data-help-title", quickTitle);
        output.Attributes.SetAttribute("data-help-summary", quickSummary);
        if (article is not null)
        {
            output.Attributes.SetAttribute("data-help-url", article.Url);
        }

        output.Content.SetHtmlContent($"""
            <button type="button"
                    class="plotline-help-icon"
                    aria-label="Help: {WebUtility.HtmlEncode(quickTitle)}"
                    data-help-tooltip="true"
                    data-help-micro="{WebUtility.HtmlEncode(micro)}">?</button>
            """);
    }
}
