namespace Netina.AdminPanel.PWA.Dialogs;

public class SubProductActionDialogBoxViewModel : BaseViewModel<SubProductSDto>
{
    private readonly ISnackbar _snackbar;
    private readonly IRestWrapper _restWrapper;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly MudDialogInstance _mudDialog;
    public SubProductActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog,
        Guid productId,
        string productName) : base(userUtility)
    {
        ProductId = productId;
        ProductName = productName;
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
    }
    public SubProductActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog,
        Guid productId,
        string productName,
        SubProductSDto subProduct) : base(userUtility)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
        ProductId = productId;
        ProductName = productName;
        SubProduct = subProduct;
        PageDto = subProduct;
    }
    private SubProductSDto? _subProduct = null;
    public SubProductSDto? SubProduct
    {
        get => _subProduct;
        set
        {
            _subProduct = value;
            if (_subProduct != null)
            {
                IsEditing = true;
            }
        }
    }
    public Guid ProductId { get; }
    public string ProductName { get; } = string.Empty;
    public void Cancel() => _mudDialog.Cancel();
    public bool IsEditing = false;

    public async Task SubmitCreateAsync()
    {
        try
        {
            if (ProductId == default)
                throw new AppException("کالای ارسالی اشتباه است");

            if (PageDto.Diversity == ProductDiversity.None)
                throw new AppException("لطفا نوع تنوع را وارد کنید");

            if (PageDto.DiversityValue.IsNullOrEmpty())
                throw new AppException("لطفا تنوع را وارد کنید");

            PageDto.DiversityDescription = $"{PageDto.Diversity.ToDisplay()} {PageDto.DiversityValue}";

            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new AppException("Token is null");
            var request = new CreateSubProductCommand(
                ProductId,
                PageDto.Diversity,
                PageDto.DiversityValue,
                PageDto.DiversityDescription,
                PageDto.PersianName,
                PageDto.Cost,
                PageDto.PackingCost,
                PageDto.Stock,
                PageDto.HasExpressDelivery,
                PageDto.MaxOrderCount,
                new List<StorageFileSDto>());

            await _restWrapper.CrudApiRest<SubProduct, Guid>(Address.SubProductController).Create<CreateSubProductCommand>(request, token);
            _mudDialog.Close(DialogResult.Ok(true));
        }
        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 SubmitEditAsync()
    {
        try
        {
            if (SubProduct == null)
                throw new AppException("محصول به درستی ارسال نشده است");

            if (ProductId == default)
                throw new AppException("کالای ارسالی اشتباه است");

            if (PageDto.Diversity == ProductDiversity.None)
                throw new AppException("لطفا نوع تنوع را وارد کنید");

            if (PageDto.DiversityValue.IsNullOrEmpty())
                throw new AppException("لطفا تنوع را وارد کنید");

            PageDto.DiversityDescription = $"{PageDto.Diversity.ToDisplay()} {PageDto.DiversityValue}";
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new AppException("Token is null");
            var request = new UpdateSubProductCommand(
                PageDto.Id,
                PageDto.ParentId,
                PageDto.Diversity,
                PageDto.DiversityValue,
                PageDto.DiversityDescription,
                PageDto.PersianName,
                PageDto.Cost,
                PageDto.PackingCost,
                PageDto.Stock,
                PageDto.HasExpressDelivery,
                PageDto.MaxOrderCount,
                new List<StorageFileSDto>());

            await _restWrapper.CrudApiRest<SubProduct, Guid>(Address.SubProductController).Update<UpdateSubProductCommand>(request, token);
            _mudDialog.Close();
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }
}