namespace Netina.AdminPanel.PWA.Pages;

public class OrdersPageViewModel : BaseViewModel<OrderDashboardDto>
{
    private readonly NavigationManager _navigationManager;
    private readonly ISnackbar _snackbar;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly IBrowserViewportService _browserViewportService;
    private readonly IRestWrapper _restWrapper;

    public string Search = string.Empty;
    public int MainGridCurrentPage = 0;
    public int MainGridPageCount = 1;

    public ObservableCollection<OrderSDto> MainOrders { get; } = new ObservableCollection<OrderSDto>();

    public OrdersPageViewModel(NavigationManager navigationManager,
        ISnackbar snackbar,
        IUserUtility userUtility,
        IRestWrapper restWrapper,
        IDialogService dialogService,
        IBrowserViewportService browserViewportService) : base(userUtility)
    {
        _navigationManager = navigationManager;
        _snackbar = snackbar;
        _userUtility = userUtility;
        _restWrapper = restWrapper;
        _dialogService = dialogService;
        _browserViewportService = browserViewportService;
    }

    public override async Task InitializeAsync()
    {
        await base.InitializeAsync();
        if (!IsPermitted)
            return;
        try
        {
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            IsProcessing = true;
            MainOrders.Clear();
            var dto = await _restWrapper.OrderRestApi.ReadAll(MainGridCurrentPage, token);
            dto.ForEach(d => MainOrders.Add(d));
            if (MainOrders.Count == 15)
                MainGridPageCount = 2;

            var orderDashboardDto = await _restWrapper.DashboardApiRest.GetOrdersDashboardAsync(token);
            PageDto = orderDashboardDto;
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (ex.StatusCode == HttpStatusCode.Unauthorized)
            {
                await _userUtility.LogoutAsync();
                _navigationManager.NavigateTo("login", true, true);
            }
            _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 ChangePageAsync(int page)
    {
        MainGridCurrentPage = page - 1;
        if (MainGridCurrentPage > MainGridPageCount - 2)
        {

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


                var dto = await _restWrapper.OrderRestApi.ReadAll(MainGridCurrentPage, token,
                    FactorCodeSearch,
                    null,
                    OrderStatusSearch?.Value,
                    null,
                    ShowOrderBags == false ? null : true);
                dto.ForEach(d => MainOrders.Add(d));
                if (MainOrders.Count % 15 == 0)
                    MainGridPageCount = MainGridCurrentPage + 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 ShowClicked(OrderSDto order)
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.False, NoHeader = true, FullWidth = true, DisableBackdropClick = true };

        var breakPoint = await _browserViewportService.GetCurrentBreakpointAsync();
        if (breakPoint == Breakpoint.Xs)
            maxWidth = new DialogOptions { FullScreen = true, CloseButton = true };

        var parameters = new DialogParameters<OrderActionDialogBox>();
        parameters.Add(x => x.Order, order);
        var dialogResult = await _dialogService.ShowAsync<OrderActionDialogBox>($" سفارش {order.FactorCode}", parameters, maxWidth);
        var result = await dialogResult.Result;
        if (!result.Canceled && result.Data is bool and true)
        {
            await InitializeAsync();
        }
    }

    public string? FactorCodeSearch { get; set; } = null;
    public bool ShowOrderBags { get; set; } = false;

    public async Task SearchAsync()
    {
        try
        {
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            IsProcessing = true;
            MainOrders.Clear();
            List<OrderSDto> dto;

            dto = await _restWrapper.OrderRestApi.ReadAll(MainGridCurrentPage, token,
                FactorCodeSearch,
                null,
                OrderStatusSearch?.Value,
                null,
                ShowOrderBags == false ? null : true);

            dto.ForEach(d => MainOrders.Add(d));
            if (MainOrders.Count == 15)
                MainGridPageCount = 2;

            var orderDashboardDto = await _restWrapper.DashboardApiRest.GetOrdersDashboardAsync(token);
            PageDto = orderDashboardDto;
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (ex.StatusCode == HttpStatusCode.Unauthorized)
            {
                await _userUtility.LogoutAsync();
                _navigationManager.NavigateTo("login", true, true);
            }
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }


    public FilterOptionDto<OrderStatus>? OrderStatusSearch;
    public List<FilterOptionDto<OrderStatus>> OrderStatusFilterOptions = new List<FilterOptionDto<OrderStatus>>
    {
        new FilterOptionDto<OrderStatus>{Title = OrderStatus.Paid.ToDisplay(),Value = OrderStatus.Paid},
        new FilterOptionDto<OrderStatus>{Title = OrderStatus.Submitted.ToDisplay(),Value = OrderStatus.Submitted},
        new FilterOptionDto<OrderStatus>{Title = OrderStatus.Delivered.ToDisplay(),Value = OrderStatus.Delivered},
        new FilterOptionDto<OrderStatus>{Title = OrderStatus.Done.ToDisplay(),Value = OrderStatus.Done},
        new FilterOptionDto<OrderStatus>{Title = OrderStatus.Canceled.ToDisplay(),Value = OrderStatus.Canceled},

    };
    public async Task<IEnumerable<FilterOptionDto<OrderStatus>>> OrderStatusSearchAsync(string orderStatus)
    {
        if (orderStatus.IsNullOrEmpty())
            return OrderStatusFilterOptions;
        return OrderStatusFilterOptions.Where(o => o.Title == orderStatus).ToList();
    }
    public async Task SearchByOrderStatusAsync(FilterOptionDto<OrderStatus>? arg)
    {
        OrderStatusSearch = arg;
        await SearchAsync();
    }

    public async Task ChangeShowOrderBagsAsync(bool? arg)
    {
        ShowOrderBags = arg ?? false;
        await SearchAsync();
    }
}