using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Contracts.Enums;
using FoodsharingSiegen.Server.Data.Service;
using FoodsharingSiegen.Server.Dialogs;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components;

namespace FoodsharingSiegen.Server.Controls
{
    public partial class ProspectContainer
    {
        #region Dependencies

        /// <summary>
        ///     Gets or sets the value of the prospect service (ab)
        /// </summary>
        [Inject]
        public ProspectService ProspectService { get; set; } = null!;

        #endregion

        #region Parameters

        [Parameter]
        public string? CssClass { get; set; }

        [Parameter]
        public Func<Task>? OnDataChanged { get; set; }

        [Parameter]
        public Prospect? Prospect { get; set; }

        [Parameter]
        public ProspectStateFilter StateFilter { get; set; }

        #endregion

        #region Private Method AddInteraction

        private async Task AddInteraction(InteractionType type)
        {
            if (Prospect != null && OnDataChanged != null)
            {
                var headerText = $"{type.Translate(AppSettings)} für {Prospect.Name} eintragen";

                Func<Task> onSuccess = async () =>
                {
                    if (type == InteractionType.IdCheck && Prospect.Images != null && Prospect.Images.Count > 0)
                    {
                        await ConfirmDialog.ShowAsync(ModalService, "Personalausweisbilder löschen?", $"Möchtest du die Personalausweisbilder von {Prospect.Name} löschen? Diese werden für die weitere Bearbeitung nicht mehr benötigt und enthalten persönliche Daten.", async () =>
                        {
                            var result = await ProspectService.DeleteVerificationImagesAsync(Prospect.Id);
                            await OnDataChanged();
                        });
                    }
                    await OnDataChanged();
                };

                await InteractionDialog.ShowAsync(ModalService, new(type, Prospect.Id, headerText, onSuccess));
            }
        }

        #endregion

        #region Private Method DeleteProspectAsync

        /// <summary>
        ///     Deletes the currently selected prospect after user confirmation. This action is irreversible and will update the record state to "Deleted".
        /// </summary>
        /// <returns>A task that represents the asynchronous delete operation.</returns>
        private async Task ArchiveProspectAsync()
        {
            if (Prospect == null) return;

            await ConfirmDialog.ShowAsync(ModalService, $"{Prospect.Name} archivieren", $"Soll {Prospect.Name} mit der FS-ID {Prospect.FsId} wirklich ins Archiv verschoben werden?", async () =>
            {
                Prospect.RecordState = RecordState.Archived;
                var updateR = await ProspectService.UpdateAsync(Prospect);
                if (updateR.Success && OnDataChanged != null) await OnDataChanged();
            });
        }

        #endregion

        #region Private Method EditProspectAsync

        private async Task EditProspectAsync()
        {
            await EditProspectDialog.ShowAsync(ModalService, OnDataChanged ?? (async () => await Task.CompletedTask), Prospect);
        }

        #endregion

        #region Private Method GetTyped

        private List<Interaction> GetTyped(InteractionType type)
        {
            return Prospect?.Interactions?.Where(x => x.Type == type).ToList() ?? [];
        }

        #endregion

        #region Private Method OpenVerificationDialogAsync

        private async Task OpenVerificationDialogAsync()
        {
            if (Prospect == null) return;
            await VerificationSettingsDialog.ShowAsync(ModalService, Prospect, OnDataChanged);
        }

        #endregion
        
        #region Private Method RemoveInteraction

        /// <summary>
        ///     Removes a specified interaction by its identifier. Displays a confirmation dialog to the user before performing the removal.
        /// </summary>
        /// <param name="arg">The unique identifier of the interaction to be removed.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        private async Task RemoveInteraction(Guid arg)
        {
            var type = Prospect?.Interactions.FirstOrDefault(x => x.Id == arg)?.Type;
            var typeName = type != null ? type.Value.Translate(AppSettings) : "Interaktion";

            await ConfirmDialog.ShowAsync(ModalService, "Bestätigen", $"{typeName} wirklich entfernen?", async () =>
            {
                var removeR = await ProspectService.RemoveInteraction(arg);
                if (removeR.Success && OnDataChanged != null) await OnDataChanged();
            });
        }

        private async Task RemoveInteraction(InteractionType type)
        {
            var typeName = type.Translate(AppSettings);
            await ConfirmDialog.ShowAsync(ModalService, "Bestätigen", $"Alle {typeName}-Interaktionen wirklich entfernen?", async () =>
            {
                var interactions = Prospect?.Interactions.Where(x => x.Type == type);

                var dataChanged = false;

                foreach (var interaction in interactions ?? [])
                {
                    var removeR = await ProspectService.RemoveInteraction(interaction.Id);
                    if (!removeR.Success) continue;

                    dataChanged = true;
                }

                if(dataChanged && OnDataChanged != null) await OnDataChanged();
            });
        }

        #endregion

        #region Private Method RestoreProspectAsync

        /// <summary>
        ///     Restores the currently selected prospect after user confirmation. This action will update the record state to "Default".
        /// </summary>
        /// <returns>A task that represents the asynchronous restore operation.</returns>
        private async Task RestoreProspectAsync()
        {
            if (Prospect == null) return;

            await ConfirmDialog.ShowAsync(ModalService, $"{Prospect.Name} wiederherstellen", $"Soll {Prospect.Name} mit der FS-ID {Prospect.FsId} wiederhergestellt werden?", async () =>
            {
                Prospect.RecordState = RecordState.Default;
                var updateR = await ProspectService.UpdateAsync(Prospect);
                if (updateR.Success && OnDataChanged != null) await OnDataChanged();
            });
        }

        #endregion
    }
}