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

namespace BackOffice.Pages.Content.Components;

public partial class SitePageSectionEditDialog
{
    [CascadingParameter] IMudDialogInstance DialogInstance { get; set; } = default!;
    [Inject] public ISitePageService SitePageService { get; set; } = default!;

    [Parameter] public SitePageSectionEditDto Model { get; set; } = new();
    [Parameter] public long? SectionId { get; set; }
    [Parameter] public bool IsEditMode { get; set; }

    private bool _isEditMode => IsEditMode && SectionId.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 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 && SectionId.HasValue)
            {
                await SitePageService.UpdateSectionAsync(SectionId.Value, Model);
            }
            else
            {
                await SitePageService.CreateSectionAsync(Model);
            }

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

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