using BackOffice.Services.Tag;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace BackOffice.Pages.Tag.Components;

public partial class AssignTagsDialog
{
    [CascadingParameter] IMudDialogInstance DialogInstance { get; set; } = default!;
    [Inject] public ITagService TagService { get; set; } = default!;

    [Parameter] public long ProductId { get; set; }
    [Parameter] public string ProductTitle { get; set; } = string.Empty;

    private List<TagListItemDto> _tags = new();
    private List<ProductTagViewDto> _currentTags = new();
    private long _selectedTagId;

    protected override async Task OnInitializedAsync()
    {
        var tagsResult = await TagService.GetTagsAsync(new TagFilterDto
        {
            PageNumber = 1,
            PageSize = 100,
            IsActive = true
        });

        _tags = tagsResult.Items;

        _currentTags = await TagService.GetProductTagsAsync(ProductId);

        await base.OnInitializedAsync();
    }

    private async Task AssignAsync()
    {
        if (_selectedTagId == 0)
            return;

        // بررسی تکراری نبودن تگ
        if (_currentTags.Any(t => t.TagId == _selectedTagId))
        {
            Snackbar.Add("این تگ قبلاً به محصول اضافه شده است", Severity.Warning);
            return;
        }

        await TagService.AssignToProductAsync(ProductId, _selectedTagId);
        Snackbar.Add("تگ به محصول اضافه شد", Severity.Success);

        _currentTags = await TagService.GetProductTagsAsync(ProductId);
        _selectedTagId = 0;
    }

    private async Task RemoveAsync(ProductTagViewDto tag)
    {
        await TagService.RemoveProductTagAsync(tag.ProductTagId);
        Snackbar.Add("تگ از محصول حذف شد", Severity.Success);
        _currentTags = await TagService.GetProductTagsAsync(ProductId);
    }

    private void Close()
    {
        DialogInstance.Close();
    }
}
