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

namespace BackOffice.Pages.Package.Components
{
    public partial class UpdateDialog
    {
        private bool _isLoading = false;
        [Inject] public PackageContract.PackageContractClient PackageContract { get; set; }
        [Inject] public ConfigurationContract.ConfigurationContractClient ConfigClient { get; set; }

        [Parameter]
        public UpdatePackageRequest Model { get; set; } = new();

        [CascadingParameter]
        IMudDialogInstance MudDialog { get; set; }

        private List<ClubFeatureModel> _features = new();
        private HashSet<long> _selectedFeatureIds = new();
        private string _srcImage = "data:image/png;base64,[encoded data, 19220 characters]";
        private IBrowserFile? _imageFile;
        private long _maxAllowedSize = (1024 * 1024) * 200;

        private async Task OnImageFileSelect(IBrowserFile? file)
        {
            _imageFile = file;
            var buffer = new byte[file.Size];
            await file.OpenReadStream().ReadAsync(buffer);
            _srcImage = $"data:{file.ContentType};base64," + Convert.ToBase64String(buffer);
            StateHasChanged();
        }
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            _srcImage = Model.ImagePath;

            // Pre-populate selected features from model
            _selectedFeatureIds = new HashSet<long>(Model.FeatureIds);

            // Load available club features
            try
            {
                var result = await ConfigClient.GetClubFeaturesAsync(new Google.Protobuf.WellKnownTypes.Empty());
                _features = result?.Features?.ToList() ?? new();
            }
            catch { /* ignore — features are optional */ }
        }

        private void ToggleFeature(long featureId, bool selected)
        {
            if (selected) _selectedFeatureIds.Add(featureId);
            else _selectedFeatureIds.Remove(featureId);
        }

        public async void CallUpdateMethod()
        {
            _isLoading = true;
            StateHasChanged();
            if (string.IsNullOrWhiteSpace(Model.Title))
            {
                Snackbar.Add("لطفا عنوان را وارد کنید!", Severity.Warning);
                _isLoading = false;
                StateHasChanged();
                return;
            }
            if (string.IsNullOrWhiteSpace(Model.Description))
            {
                Snackbar.Add("لطفا توضیحات را وارد کنید!", Severity.Warning);
                _isLoading = false;
                StateHasChanged();
                return;
            }
            if (_imageFile != null)
            {
                var imageBuffers = new byte[_imageFile.Size];
                await _imageFile.OpenReadStream(_maxAllowedSize).ReadAsync(imageBuffers);
                Model.ImageFile = new()
                {
                    File = ByteString.CopyFrom(imageBuffers),
                    Mime = _imageFile.ContentType,
                    FileName = Path.GetFileNameWithoutExtension(_imageFile.Name)
                };
            }

            try
            {
                Model.FeatureIds.Clear();
                Model.FeatureIds.AddRange(_selectedFeatureIds);
                await PackageContract.UpdatePackageAsync(Model);
                Submit();

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

            _isLoading = false;
            StateHasChanged();
        }

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