using Mapster;
using NetinaShop.Domain.Entities.Users;
using NetinaShop.Domain.Models.Claims;

namespace NetinaShop.AdminPanel.PWA.Dialogs;

public class UserActionDialogBoxViewModel : BaseViewModel<UserActionRequestDto>
{

    private readonly ISnackbar _snackbar;
    private readonly IRestWrapper _restWrapper;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly MudDialogInstance _mudDialog;


    public UserActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
    }

    public UserActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog,
        ApplicationUserSDto user)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
        PageDto.UserId = user.Id;
        IsEditing = true;
    }
    public bool IsEditing = false;



    public override async Task InitializeAsync()
    {
        if (IsEditing && PageDto.UserId != default)
        {
            try
            {
                var token = await _userUtility.GetBearerTokenAsync();
                if (token == null)
                    throw new Exception("Token is null");
                IsProcessing = true;
                var user = await _restWrapper.UserRestApi.ReadOne(PageDto.UserId, token);
                PageDto = user.Adapt<UserActionRequestDto>();
                PageDto.UserId = user.Id;
                if (PageDto.RoleIds.Count > 0)
                {

                    var role = await _restWrapper.RoleRestApi.ReadOne(PageDto.RoleIds.FirstOrDefault(), token);
                    if (role != null)
                        SelectedRole = new ApplicationRole
                        {
                            Id = role.RoleId,
                            Name = role.EnglishName,
                            PersianName = role.PersianName
                        };
                }

            }
            catch (ApiException ex)
            {
                var exe = await ex.GetContentAsAsync<ApiResult>();
                if (exe != null)
                    _snackbar.Add(exe.Message, Severity.Error);
                _snackbar.Add(ex.Content, Severity.Error);
            }
            catch (Exception e)
            {
                _snackbar.Add(e.Message, Severity.Error);
            }
            finally
            {

                IsProcessing = false;
            }
        };
    }



    private List<ApplicationRole> _roles = new List<ApplicationRole>();
    public ApplicationRole? SelectedRole;
    public async Task<IEnumerable<ApplicationRole>> SearchRole(string roleName)
    {
        try
        {
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            if (roleName.IsNullOrEmpty())
                _roles = await _restWrapper.RoleRestApi.ReadAll(0, token);
            else
                _roles = await _restWrapper.RoleRestApi.ReadAll(roleName, token);
            return _roles;
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                _snackbar.Add(exe.Message, Severity.Error);
            _snackbar.Add(ex.Content, Severity.Error);
            return _roles;
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            return _roles;
        }
    }

    public void Cancel() => _mudDialog.Cancel();

    public async Task SubmitEditAsync()
    {
        try
        {
            IsProcessing = true;
            if (PageDto.UserId == default)
                throw new Exception("Id is null !");

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            if (PageDto.FirstName.IsNullOrEmpty())
                throw new Exception("نام را وارد کنید");

            if (PageDto.LastName.IsNullOrEmpty())
                throw new Exception("نام خانوادگی را وارد کنید");

            if (PageDto.PhoneNumber.IsNullOrEmpty())
                throw new Exception("شماره تلفن را وارد کنید");

            if (SelectedRole == null)
                throw new Exception("نقش را انتخاب کنید");

            PageDto.RoleIds.Clear();
            PageDto.RoleIds.Add(SelectedRole.Id);

            await _restWrapper.UserRestApi.UpdateUserAsync(PageDto, token);
            _snackbar.Add($"ویرایش {PageDto.FirstName + " " + PageDto.LastName} با موفقیت انجام شد", Severity.Success);
            _mudDialog.Close(DialogResult.Ok(true));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                _snackbar.Add(exe.Message, Severity.Error);
            _snackbar.Add(ex.Content, Severity.Error);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }
    public async Task SubmitCreateAsync()
    {
        try
        {
            IsProcessing = true;

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            if (PageDto.FirstName.IsNullOrEmpty())
                throw new Exception("نام را وارد کنید");

            if (PageDto.LastName.IsNullOrEmpty())
                throw new Exception("نام خانوادگی را وارد کنید");

            if (PageDto.PhoneNumber.IsNullOrEmpty())
                throw new Exception("شماره تلفن را وارد کنید");

            if (SelectedRole == null)
                throw new Exception("نقش را انتخاب کنید");


            PageDto.RoleIds.Clear();
            PageDto.RoleIds.Add(SelectedRole.Id);

            await _restWrapper.UserRestApi.CreateUserAsync(PageDto, token);

            _snackbar.Add($"ساخت کاربر {PageDto.FirstName + " "+ PageDto.LastName} با موفقیت انجام شد", Severity.Success);
            _mudDialog.Close(DialogResult.Ok(true));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                _snackbar.Add(exe.Message, Severity.Error);
            _snackbar.Add(ex.Content, Severity.Error);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }
}