using MudBlazor;
using NetinaShop.Domain.Entities.Discounts;

namespace NetinaShop.AdminPanel.PWA.Pages;

public class DiscountPageViewModel : BaseViewModel<ObservableCollection<DiscountSDto>>
{
    private readonly NavigationManager _navigationManager;
    private readonly ISnackbar _snackbar;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly IRestWrapper _restWrapper;

    public string Search = string.Empty;
    public int CurrentPage = 0;
    public int PageCount = 1;

    public DiscountPageViewModel(NavigationManager navigationManager, ISnackbar snackbar, IUserUtility userUtility, IRestWrapper restWrapper, IDialogService dialogService)
    {
        _navigationManager = navigationManager;
        _snackbar = snackbar;
        _userUtility = userUtility;
        _restWrapper = restWrapper;
        _dialogService = dialogService;
    }

    public override async Task InitializeAsync()
    {
        try
        {
            IsProcessing = true;
            PageDto.Clear();

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            var dto = await _restWrapper.DiscountRest.ReadAll(CurrentPage, token);
            dto.ForEach(d => PageDto.Add(d));
            if (PageDto.Count == 15)
                PageCount = 2;
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
        await base.InitializeAsync();
    }

    public async Task ChangePageAsync(int page)
    {
        CurrentPage = page - 1;
        if (CurrentPage > PageCount - 2)
        {

            try
            {
                IsProcessing = true;

                var token = await _userUtility.GetBearerTokenAsync();
                if (token == null)
                    throw new Exception("Token is null");
                List<DiscountSDto> dto = new List<DiscountSDto>();
                if (Search.IsNullOrEmpty())
                {
                    dto = await _restWrapper.DiscountRest.ReadAll(CurrentPage, token);
                }
                else
                {
                    dto = await _restWrapper.DiscountRest.ReadAll(CurrentPage, Search, token);
                }

                dto.ForEach(d => PageDto.Add(d));
                if (PageDto.Count % 20 == 0)
                    PageCount = CurrentPage + 2;

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

                IsProcessing = false;
            }
        }
    }

    public async Task AddAsync()
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Medium, FullWidth = true, DisableBackdropClick = true };
        var dialogResult = await _dialogService.ShowAsync<DiscountActionDialogBox>("افزودن تخفیف جدید", maxWidth);
        var result = await dialogResult.Result;
        if (!result.Canceled && result.Data is bool and true)
        {
            await InitializeAsync();
        }
    }

    public async Task EditAsync(DiscountSDto discount)
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Medium, FullWidth = true, DisableBackdropClick = true };
        var parameters = new DialogParameters<DiscountActionDialogBox>();
        parameters.Add(x => x.Discount, discount);
        var dialogResult= await _dialogService.ShowAsync<DiscountActionDialogBox>($"ویرایش تخفیف {discount.Code}", parameters, maxWidth);
        var result = await dialogResult.Result;
        if (!result.Canceled && result.Data is bool and true)
        {
            await InitializeAsync();
        }
    }

    public async Task DeleteAsync(Guid selectedDiscountId)
    {
        var options = new DialogOptions { CloseOnEscapeKey = true };
        var parameters = new DialogParameters<QuestionDialog>();
        parameters.Add(x => x.ContentText, "آیا از حذف تخفیف اطمینان دارید ?");
        var dialogReference = await _dialogService.ShowAsync<QuestionDialog>("حذف تخفیف", parameters, options);
        var result = await dialogReference.Result;
        if (!result.Canceled)
        {

            try
            {

                IsProcessing = true;
                var token = await _userUtility.GetBearerTokenAsync();
                if (token == null)
                    throw new Exception("Token is null");
                await _restWrapper.CrudDtoApiRest<Discount, DiscountSDto, Guid>(Address.DiscountController)
                    .Delete(selectedDiscountId, token);
                _snackbar.Add("حذف تخفیف با موفقیت انجام شد", Severity.Success);

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

                IsProcessing = false;
            }
        }
    }

    public async Task SearchChanged(string search)
    {
        if (search.IsNullOrEmpty() && !Search.IsNullOrEmpty())
            await InitializeAsync();
        Search = search;
    }
    public async Task SearchAsync()
    {
        try
        {
            if (Search.IsNullOrEmpty())
                throw new AppException("کد تخفیفــ برای جست جو وارد نشده است");

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            IsProcessing = true;
            CurrentPage = 0;
            PageCount = 1;
            PageDto.Clear();
            var dto = await _restWrapper.DiscountRest.ReadAll(CurrentPage, Search, token);
            dto.ForEach(d => PageDto.Add(d));
            if (PageDto.Count == 20)
                PageCount = 2;
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }

}