@using CMSMicroservice.Protobuf.Protos.ClubMembership
@using CMSMicroservice.Protobuf.Protos.Package
@using BackOffice.Pages.AutoComplete

<MudDialog>
    <DialogContent>
        <MudForm @ref="_form" @bind-IsValid="_formValid">
            <MudStack Spacing="3">
                <UserAutoComplete Label="انتخاب کاربر" @bind-SelectedUserId="_model.UserId" />

                @if (_isLoadingPackages)
                {
                    <MudSkeleton SkeletonType="SkeletonType.Rectangle" Height="56px" />
                }
                else
                {
                    <MudSelect T="long" @bind-Value="_model.PackageId"
                               Label="انتخاب پکیج"
                               Required="true"
                               RequiredError="انتخاب پکیج الزامی است"
                               Variant="Variant.Outlined"
                               AnchorOrigin="Origin.BottomCenter">
                        @foreach (var pkg in _packages)
                        {
                            <MudSelectItem T="long" Value="pkg.Id">
                                @pkg.Title — @($"{pkg.Price:N0}") ریال
                            </MudSelectItem>
                        }
                    </MudSelect>
                }

                <MudAlert Severity="Severity.Info" Dense="true">
                    <MudText Typo="Typo.body2">
                        با تایید، عضویت باشگاه برای کاربر فعال می‌شود.
                        <br/>
                        <small>عضویت باشگاه بدون محدودیت زمانی است.</small>
                    </MudText>
                </MudAlert>
            </MudStack>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">لغو</MudButton>
        <MudButton Color="Color.Success" 
                   Variant="Variant.Filled" 
                   OnClick="Submit"
                   Disabled="@(!_formValid || _isSubmitting || _isLoadingPackages)">
            @if (_isSubmitting)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" />
                <MudText Class="ms-2">در حال پردازش...</MudText>
            }
            else
            {
                <text>تایید و فعال‌سازی</text>
            }
        </MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; }
    [Inject] public ClubMembershipContract.ClubMembershipContractClient ClubContract { get; set; }
    [Inject] public PackageContract.PackageContractClient PackageClient { get; set; }

    private MudForm _form;
    private bool _formValid;
    private bool _isSubmitting;
    private bool _isLoadingPackages = true;
    private List<GetAllPackageByFilterResponseModel> _packages = new();
    private ActivateModel _model = new();

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

    private async Task LoadPackages()
    {
        _isLoadingPackages = true;
        try
        {
            var request = new GetAllPackageByFilterRequest
            {
                PaginationState = new CMSMicroservice.Protobuf.Protos.PaginationState
                {
                    PageNumber = 1,
                    PageSize = 50
                }
            };
            var result = await PackageClient.GetAllPackageByFilterAsync(request);
            if (result?.Models != null)
            {
                _packages = result.Models.ToList();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری پکیج‌ها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isLoadingPackages = false;
        }
    }

    private void Cancel() => MudDialog.Cancel();

    private async Task Submit()
    {
        await _form.Validate();
        if (!_formValid) return;

        if (!_model.UserId.HasValue || _model.UserId.Value <= 0)
        {
            Snackbar.Add("لطفاً کاربر را انتخاب کنید.", Severity.Warning);
            return;
        }

        if (_model.PackageId <= 0)
        {
            Snackbar.Add("لطفاً پکیج را انتخاب کنید.", Severity.Warning);
            return;
        }

        _isSubmitting = true;
        try
        {
            var request = new ActivateClubMembershipRequest
            {
                UserId = _model.UserId.Value,
                PackageId = _model.PackageId,
                ForceActivation = true
            };

            var response = await ClubContract.ActivateClubMembershipAsync(request);
            
            Snackbar.Add("عضویت با موفقیت فعال شد.", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
        }
    }

    private class ActivateModel
    {
        public long? UserId { get; set; }
        public long PackageId { get; set; }
    }
}
