using CMSMicroservice.Protobuf.Protos.NetworkMembership;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace BackOffice.Pages.Network.Components;

public partial class ChangeParentDialog
{
    [Parameter] public long UserId { get; set; }
    [Parameter] public string UserDisplayName { get; set; } = "";
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;

    [Inject] public NetworkMembershipContract.NetworkMembershipContractClient NetworkContract { get; set; } = default!;

    private MudForm _form = default!;
    private long _newParentId;
    private int _newLeg;
    private string _reason = "";
    private bool _isSubmitting;

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

        if (_newParentId == UserId)
        {
            Snackbar.Add("والد جدید نمی‌تواند خود کاربر باشد.", Severity.Error);
            return;
        }

        _isSubmitting = true;
        StateHasChanged();

        try
        {
            var request = new ChangeNetworkParentRequest
            {
                UserId = UserId,
                NewParentId = _newParentId,
                NewLeg = _newLeg,
                Reason = _reason
            };

            await NetworkContract.ChangeNetworkParentAsync(request);
            Snackbar.Add("والد کاربر با موفقیت تغییر کرد.", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Grpc.Core.RpcException ex)
        {
            Snackbar.Add($"خطا: {ex.Status.Detail}", Severity.Error);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در تغییر والد: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
            StateHasChanged();
        }
    }

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