using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Markdig.Syntax;

namespace MarkdownEditor.Views.Renderers;

/// <summary>
/// Renders markdown list blocks (ordered and unordered).
/// </summary>
public class ListRenderer : IMarkdownBlockRenderer
{
    private readonly MarkdownRendererCoordinator _coordinator;

    /// <summary>
    /// Initializes a new instance of the <see cref="ListRenderer"/> class.
    /// </summary>
    /// <param name="coordinator">The coordinator for rendering nested blocks.</param>
    public ListRenderer(MarkdownRendererCoordinator coordinator)
    {
        _coordinator = coordinator;
    }

    /// <inheritdoc/>
    public bool CanRender(Block block) => block is ListBlock;

    /// <inheritdoc/>
    public Control? Render(Block block)
    {
        if (block is not ListBlock list)
        {
            return null;
        }

        var panel = new StackPanel { Margin = new Thickness(20, 5, 0, 5) };

        int index = 1;
        foreach (var item in list)
        {
            if (item is ListItemBlock listItem)
            {
                var itemPanel = new StackPanel();
                foreach (var childBlock in listItem)
                {
                    var control = _coordinator.RenderBlock(childBlock);
                    if (control != null)
                    {
                        itemPanel.Children.Add(control);
                    }
                }

                var bullet = list.IsOrdered ? $"{index}. " : "• ";
                var itemControl = new DockPanel
                {
                    Children =
                    {
                        new TextBlock
                        {
                            Text = bullet,
                            [DockPanel.DockProperty] = Dock.Left,
                            VerticalAlignment = VerticalAlignment.Top,
                            Margin = new Thickness(0, 0, 5, 0)
                        },
                        itemPanel
                    }
                };

                panel.Children.Add(itemControl);
                index++;
            }
        }

        return panel;
    }
}

