using CMSMicroservice.Protobuf.Protos.Products;
using Google.Protobuf;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;

namespace BackOffice.Pages.Products.Components;

public partial class CreateDialog
{
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] public ProductsContract.ProductsContractClient ProductsContract { get; set; } = default!;
    [Parameter] public CreateNewProductsRequest Model { get; set; } = default!;

    private IBrowserFile? _mainImageFile;
    private IBrowserFile? _thumbnailImageFile;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;
    private bool _isLoading;
    private string? _mainImagePreview;
    private string? _thumbnailPreview;
    private byte[]? _mainImageBuffer;
    private byte[]? _thumbnailImageBuffer;
    private List<long> _selectedCategoryIds = new();

    private async Task OnMainImageSelected(IBrowserFile? file)
    {
        _mainImageFile = file;
        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _mainImageBuffer = ms.ToArray();
            _mainImagePreview = $"data:{file.ContentType};base64," + Convert.ToBase64String(_mainImageBuffer);
            StateHasChanged();
        }
    }

    private async Task OnThumbnailSelected(IBrowserFile? file)
    {
        _thumbnailImageFile = file;
        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _thumbnailImageBuffer = ms.ToArray();
            _thumbnailPreview = $"data:{file.ContentType};base64," + Convert.ToBase64String(_thumbnailImageBuffer);
            StateHasChanged();
        }
    }

    public async Task CallCreateMethod()
    {
        _isLoading = true;
        StateHasChanged();

        if (string.IsNullOrWhiteSpace(Model.Title))
        {
            Snackbar.Add("لطفا عنوان را وارد کنید!", Severity.Warning);
            _isLoading = false;
            StateHasChanged();
            return;
        }

        if (_mainImageFile != null && _mainImageBuffer != null)
        {
            Model.ImageFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(_mainImageBuffer),
                Mime = _mainImageFile.ContentType,
                FileName = Path.GetFileNameWithoutExtension(_mainImageFile.Name)
            };
        }

        if (_thumbnailImageFile != null && _thumbnailImageBuffer != null)
        {
            Model.ThumbnailFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(_thumbnailImageBuffer),
                Mime = _thumbnailImageFile.ContentType,
                FileName = Path.GetFileNameWithoutExtension(_thumbnailImageFile.Name)
            };
        }

        try
        {
            Model.CategoryIds.Clear();
            Model.CategoryIds.AddRange(_selectedCategoryIds);

            var createResponse = await ProductsContract.CreateNewProductsAsync(Model);

            Submit();
        }
        catch
        {
            Snackbar.Add("خطای سرور", Severity.Error);
        }

        _isLoading = false;
        StateHasChanged();
    }

    void Submit() => MudDialog.Close(DialogResult.Ok(true));
    void Cancel() => MudDialog.Cancel();
}
