using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Contracts.Model;
using FoodsharingSiegen.Server.Data.Service;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.Options;

namespace FoodsharingSiegen.Server.Pages
{
    public partial class UploadVerification : ComponentBase
    {
        [Inject]
        public ProspectService ProspectService { get; set; } = null!;

        [Inject]
        public IOptions<AppSettings> AppSettings { get; set; } = null!;

        [Parameter]
        public Guid Token { get; set; }

        private bool _isLoading = true;
        private Prospect? _prospect;
        
        private int _uploadedCount = 0;
        private bool _isUploading = false;
        
        private string? _message;
        private bool _isSuccess;
        
        private const int MaxAllowedFiles = 5;
        private const long MaxFileSize = 10 * 1024 * 1024; // 10 MB

        protected override async Task OnInitializedAsync()
        {
            await LoadData();
        }

        private async Task LoadData()
        {
            _isLoading = true;
            
            try
            {
                var result = await ProspectService.GetProspectByVerificationTokenAsync(Token);
                
                if (result.Success && result.Data != null)
                {
                    _prospect = result.Data;
                    _uploadedCount = _prospect.Images?.Count ?? 0;
                }
                else
                {
                    _prospect = null;
                    _message = result.Exception?.Message ?? "Ein Fehler ist aufgetreten.";
                    _isSuccess = false;
                }
            }
            catch (Exception ex)
            {
                _message = $"Fehler: {ex.Message}";
                _isSuccess = false;
            }
            finally
            {
                _isLoading = false;
            }
        }

        private async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            if (_prospect == null) return;
            
            _message = null;
            
            var files = e.GetMultipleFiles(MaxAllowedFiles);
            
            if (_uploadedCount + files.Count > MaxAllowedFiles)
            {
                _message = $"Es sind maximal {MaxAllowedFiles} Bilder erlaubt.";
                _isSuccess = false;
                return;
            }

            _isUploading = true;
            
            int successCount = 0;
            
            foreach (var file in files)
            {
                try
                {
                    if (file.Size > MaxFileSize)
                    {
                        _message = $"Bild '{file.Name}' überschreitet die erlaubte Größe von 10 MB.";
                        _isSuccess = false;
                        continue;
                    }

                    // Resize the image to a max dimension of 1000 pixels (longest edge) to save DB space
                    var resizedImageFile = await file.RequestImageFileAsync(file.ContentType, 1000, 1000);
                    
                    using var stream = resizedImageFile.OpenReadStream(MaxFileSize);
                    using var memoryStream = new MemoryStream();
                    
                    await stream.CopyToAsync(memoryStream);
                    
                    byte[] imageData = memoryStream.ToArray();
                    
                    var saveResult = await ProspectService.AddVerificationImageAsync(_prospect.Id, imageData, resizedImageFile.ContentType);
                    
                    if (saveResult.Success)
                    {
                        successCount++;
                    }
                    else
                    {
                        _message = $"Fehler beim Speichern von {file.Name}: {saveResult.Exception?.Message}";
                        _isSuccess = false;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    _message = $"Fehler bei {file.Name}: {ex.Message}";
                    _isSuccess = false;
                }
            }

            _isUploading = false;
            
            if (successCount > 0)
            {
                _message = $"{successCount} Bild(er) erfolgreich hinzugefügt.";
                _isSuccess = true;
                _uploadedCount += successCount;
            }
            
            StateHasChanged();
        }
    }
}
