using BackOffice.Services.Blog;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;

namespace BackOffice.Pages.Blog.Components;

public partial class BlogPostEditDialog
{
    [CascadingParameter] IMudDialogInstance DialogInstance { get; set; } = default!;
    [Inject] public IBlogPostService BlogPostService { get; set; } = default!;

    [Parameter] public BlogPostEditDto Model { get; set; } = new();
    [Parameter] public long? PostId { get; set; }
    [Parameter] public bool IsEditMode { get; set; }
    [Parameter] public List<BlogCategoryItemDto> Categories { get; set; } = new();

    private bool _isEditMode => IsEditMode && PostId.HasValue;
    private MudForm? _form;
    private bool _isValid = true;
    private bool _loading;

    private IBrowserFile? _imageFile;
    private byte[]? _imageBuffer;
    private string? _imagePreview;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;

    private IEnumerable<long> _selectedCategoryIds
    {
        get => Model.CategoryIds;
        set => Model.CategoryIds = value.ToList();
    }

    private string GetCategorySelectionText(List<string> selectedValues)
    {
        if (selectedValues == null || !selectedValues.Any())
            return "انتخاب دسته‌بندی";

        var names = new List<string>();
        foreach (var val in selectedValues)
        {
            if (long.TryParse(val, out var id))
            {
                var cat = Categories.FirstOrDefault(c => c.Id == id);
                if (cat != null) names.Add(cat.Title);
            }
        }

        return names.Any() ? string.Join("، ", names) : "انتخاب دسته‌بندی";
    }

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

    private async Task HandleValidSubmit()
    {
        await SubmitAsync();
    }

    private async Task SubmitAsync()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_isValid) return;
        }

        _loading = true;

        // Handle image upload
        if (_imageFile != null && _imageBuffer != null)
        {
            Model.ImageFile = _imageBuffer;
            Model.ImageMime = _imageFile.ContentType;
            Model.ImageFileName = Path.GetFileNameWithoutExtension(_imageFile.Name);
        }

        try
        {
            if (_isEditMode && PostId.HasValue)
            {
                await BlogPostService.UpdateAsync(PostId.Value, Model);
            }
            else
            {
                await BlogPostService.CreateAsync(Model);
            }

            DialogInstance.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

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