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

namespace BackOffice.Pages.Products.Components;

public partial class GalleryDialog
{
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] public ProductsContract.ProductsContractClient ProductsContract { get; set; } = default!;
    [Inject] private IConfiguration Configuration { get; set; } = default!;

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

    private List<GalleryItemViewModel> Items { get; set; } = new List<GalleryItemViewModel>();
    private IBrowserFile? _file;
    private string? _title;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;
    private bool _isUploading;
    private string? _previewImage;
    private byte[]? _imageBuffer;

    protected override async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(_title))
            _title = ProductTitle;

        await LoadGallery();
    }

    private async Task LoadGallery()
    {
        var response = await ProductsContract.GetProductGalleryAsync(new GetProductGalleryRequest
        {
            ProductId = ProductId
        });

        Items = response?.Items?
            .Select(x => new GalleryItemViewModel
            {
                ProductGalleryId = x.ProductGalleryId,
                ProductImageId = x.ProductImageId,
                Title = x.Title,
                ImagePath = x.ImagePath,
                ImageThumbnailPath = x.ImageThumbnailPath
            })
            .ToList() ?? new List<GalleryItemViewModel>();
        StateHasChanged();
    }

    private async Task OnImageSelected(IBrowserFile? file)
    {
        _file = file;
        _previewImage = null;
        _imageBuffer = null;

        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _imageBuffer = ms.ToArray();
            _previewImage = $"data:{file.ContentType};base64," + Convert.ToBase64String(_imageBuffer);
            StateHasChanged();
        }
    }

    private async Task AddImage()
    {
        if (_file == null)
            return;

        _isUploading = true;
        StateHasChanged();

        if (_imageBuffer == null)
        {
            using var ms = new MemoryStream();
            await _file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _imageBuffer = ms.ToArray();
        }

        var request = new AddProductImageRequest
        {
            ProductId = ProductId,
            Title = _title ?? string.Empty,
            ImageFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(_imageBuffer),
                Mime = _file.ContentType,
                FileName = Path.GetFileNameWithoutExtension(_file.Name)
            }
        };

        await ProductsContract.AddProductImageAsync(request);

        _file = null;
        _title = string.Empty;
        _previewImage = null;
        _imageBuffer = null;

        await LoadGallery();

        _isUploading = false;
        StateHasChanged();
    }

    private async Task OpenPreview(GalleryItemViewModel item)
    {
        if (string.IsNullOrWhiteSpace(item.ImagePath))
            return;

        var parameters = new DialogParameters<ImagePreviewDialog>
        {
            { x => x.ImageUrl, GetFullImageUrl(item.ImagePath) },
            { x => x.Title, item.Title }
        };

        await DialogService.ShowAsync<ImagePreviewDialog>("پیش‌نمایش تصویر", parameters,
            new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true });
    }

    private async Task RemoveImage(GalleryItemViewModel item)
    {
        await ProductsContract.RemoveProductImageAsync(new RemoveProductImageRequest
        {
            ProductGalleryId = item.ProductGalleryId
        });

        await LoadGallery();
    }

    private void Close() => MudDialog.Close();

    private string GetFullImageUrl(string? path)
    {
        if (string.IsNullOrWhiteSpace(path)) return string.Empty;
        if (path.StartsWith("data:") || path.StartsWith("http")) return path;
        var baseUrl = Configuration["GwUrl"]?.TrimEnd('/') ?? "";
        return baseUrl + path;
    }

    private class GalleryItemViewModel
    {
        public long ProductGalleryId { get; set; }
        public long ProductImageId { get; set; }
        public string Title { get; set; }
        public string ImagePath { get; set; }
        public string ImageThumbnailPath { get; set; }
    }
}
