@using Microsoft.AspNetCore.Components.Forms

<MudStack Spacing="2">
    <MudText Typo="Typo.subtitle2">گالری تصاویر محصول</MudText>

    <MudFileUpload T="IReadOnlyList<IBrowserFile>"
                   Accept="image/*"
                   AppendMultipleFiles="true"
                   OnFilesChanged="OnFilesSelected">
        <ActivatorContent>
            <MudButton HtmlTag="label"
                       Variant="Variant.Filled"
                       Color="Color.Primary"
                       StartIcon="@Icons.Material.Filled.Collections"
                      >
                انتخاب تصاویر (چندتایی)
            </MudButton>
        </ActivatorContent>
    </MudFileUpload>

    @if (_items.Count == 0)
    {
        <MudText Typo="Typo.caption" Color="Color.Secondary">
            هنوز تصویری اضافه نشده است.
        </MudText>
    }
    else
    {
        <MudGrid Spacing="2">
            @foreach (var item in _items)
            {
                <MudItem xs="6" sm="4" md="3">
                    <MudPaper Class="pa-1"
                              Style="cursor:move;"
                              @ondragstart="@(() => OnDragStart(item))"
                              @ondragover:preventDefault="true"
                              @ondrop="@(() => OnDrop(item))"
                              draggable="true">
                        <div style="position:relative;">
                            <img src="@item.PreviewUrl"
                                 alt="@item.Title"
                                 style="width:100%; height:140px; object-fit:cover; border-radius:4px;" />
                            <MudIconButton Icon="@Icons.Material.Filled.Close"
                                           Color="Color.Error"
                                           Size="Size.Small"
                                           Style="position:absolute; top:4px; right:4px;"
                                           OnClick="@(() => Remove(item))" />
                        </div>
                        <MudTextField @bind-Value="item.Title"
                                      Label="عنوان"
                                      Variant="Variant.Outlined"
                                      Margin="Margin.Dense"
                                      Immediate="true"
                                      OnBlur="OnItemsChanged" />
                    </MudPaper>
                </MudItem>
            }
        </MudGrid>
    }
</MudStack>

@code {
    [Parameter] public List<ProductImageItem> Images { get; set; } = new();
    [Parameter] public EventCallback<List<ProductImageItem>> ImagesChanged { get; set; }

    private readonly List<ProductImageItem> _items = new();
    private ProductImageItem? _dragging;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;

    protected override void OnInitialized()
    {
        if (Images != null && Images.Count > 0)
        {
            _items.AddRange(Images.Select(x => new ProductImageItem
            {
                Id = x.Id == Guid.Empty ? Guid.NewGuid() : x.Id,
                Title = x.Title,
                PreviewUrl = x.PreviewUrl,
                SortOrder = x.SortOrder
            })
            .OrderBy(x => x.SortOrder));
        }
    }

    private async Task OnFilesSelected(InputFileChangeEventArgs args)
    {
        var files = args.GetMultipleFiles();
        foreach (var file in files)
        {
            if (file == null) continue;

            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            var buffer = ms.ToArray();
            var preview = $"data:{file.ContentType};base64," + Convert.ToBase64String(buffer);

            _items.Add(new ProductImageItem
            {
                Id = Guid.NewGuid(),
                Title = file.Name,
                PreviewUrl = preview,
                SortOrder = _items.Count
            });
        }

        await OnItemsChanged();
    }

    private async Task OnItemsChanged()
    {
        if (ImagesChanged.HasDelegate)
        {
            var ordered = _items
                .Select((x, index) =>
                {
                    x.SortOrder = index;
                    return x;
                })
                .ToList();

            await ImagesChanged.InvokeAsync(ordered);
        }
    }

    private void OnDragStart(ProductImageItem item)
    {
        _dragging = item;
    }

    private async Task OnDrop(ProductImageItem target)
    {
        if (_dragging == null || ReferenceEquals(_dragging, target))
            return;

        var fromIndex = _items.IndexOf(_dragging);
        var toIndex = _items.IndexOf(target);

        if (fromIndex < 0 || toIndex < 0 || fromIndex == toIndex)
            return;

        _items.RemoveAt(fromIndex);
        _items.Insert(toIndex, _dragging);
        _dragging = null;

        await OnItemsChanged();
        StateHasChanged();
    }

    private async Task Remove(ProductImageItem item)
    {
        _items.Remove(item);
        await OnItemsChanged();
        StateHasChanged();
    }

    public class ProductImageItem
    {
        public Guid Id { get; set; }
        public string Title { get; set; } = string.Empty;
        public string PreviewUrl { get; set; } = string.Empty;
        public int SortOrder { get; set; }
    }
}