using Blazorise;
using Microsoft.AspNetCore.Components;
using Server.Data;
using Address = Server.Model.Address;

namespace Server.Components.Dialogs
{
    public partial class AddressSelector : ComponentBase
    {
        #region Dependencies

        [Inject]
        private IModalService ModalService { get; set; } = null!;

        #endregion

        #region Parameters

        /// <summary>
        ///     Gets or sets the delegate that will be invoked when an address is selected.
        /// </summary>
        /// <remarks>
        ///     This property expects a <see cref="Func{T, TResult}" /> delegate where the input parameter is an <see cref="Address" />
        ///     and the return type is a <see cref="Task" />. It allows customization of what should happen when a user selects an address
        ///     from the AddressSelector component.
        /// </remarks>
        [Parameter]
        public Func<Address, Task>? OnSelected { get; set; }

        #endregion

        #region Private Properties

        private Address? SelectedCustomer { get; set; }

        #endregion

        #region Override SetParametersAsync

        //// <inheritdoc />
        public override async Task SetParametersAsync(ParameterView parameters)
        {
            parameters.SetParameterProperties(this);
            await CustomerData.LoadAsync();
            await base.SetParametersAsync(ParameterView.Empty);
        }

        #endregion

        #region Public Method ShowAsync

        /// <summary>
        ///     Displays the AddressSelector component as a modal dialog asynchronously.
        /// </summary>
        /// <param name="modalService">The service used to show the modal dialog.</param>
        /// <param name="onSelected">The callback to invoke when an address is selected.</param>
        /// <returns>
        ///     A Task that represents the asynchronous operation of showing the modal dialog.
        /// </returns>
        public static Task ShowAsync(IModalService modalService, Func<Address, Task> onSelected)
        {
            return modalService.Show<AddressSelector>(builder => { builder.Add(x => x.OnSelected, onSelected); });
        }

        #endregion

        #region Private Method SelectedAsync

        /// <summary>
        ///     Handles the selection of an address asynchronously.
        ///     Invokes the OnSelected callback with the selected address
        ///     and hides the modal service upon completion.
        /// </summary>
        /// <returns>
        ///     A Task that represents the asynchronous operation.
        /// </returns>
        private async Task SelectedAsync()
        {
            if (SelectedCustomer != null && OnSelected != null) await OnSelected.Invoke(SelectedCustomer);
            await ModalService.Hide();
        }

        #endregion
    }
}