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

namespace BackOffice.Pages.Content.Components;

public partial class PageImageEditDialog
{
    [CascadingParameter] IMudDialogInstance DialogInstance { get; set; } = default!;
    [Inject] public ISitePageSettingsService PageSettingsService { get; set; } = default!;

    [Parameter] public SavePageImageDto Model { get; set; } = new();
    [Parameter] public string PageKey { get; set; } = string.Empty;
    [Parameter] public bool IsNew { get; set; }
    [Parameter] public string? ExistingImagePath { get; set; }

    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 SubmitAsync()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_isValid) return;
        }

        _loading = true;

        if (_imageFile != null && _imageBuffer != null)
        {
            Model.ImageFile = _imageBuffer;
            Model.ImageMime = _imageFile.ContentType;
            Model.ImageFileName = Path.GetFileNameWithoutExtension(_imageFile.Name);
        }
        else if (IsNew && _imageBuffer == null)
        {
            Snackbar.Add("لطفاً یک تصویر انتخاب کنید", Severity.Warning);
            _loading = false;
            return;
        }

        try
        {
            var result = await PageSettingsService.SaveImageAsync(Model);
            if (result.Success)
            {
                DialogInstance.Close(DialogResult.Ok(true));
            }
            else
            {
                Snackbar.Add("خطا در ذخیره تصویر", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private Dictionary<string, string> GetAvailableGroups() => PageKey switch
    {
        "about" => new Dictionary<string, string>
        {
            { "team", "اعضای تیم" },
            { "values", "ارزش‌ها" }
        },
        "licenses" => new Dictionary<string, string>
        {
            { "licenses", "مجوزها" }
        },
        "landing" => new Dictionary<string, string>
        {
            { "values", "ارزش‌ها" }
        },
        _ => new Dictionary<string, string>
        {
            { "values", "ارزش‌ها" },
            { "team", "اعضای تیم" },
            { "licenses", "مجوزها" }
        }
    };

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