using Microsoft.AspNetCore.Components;
using DateTimeConverterCL;
using FrontOffice.Main.Utilities;

namespace FrontOffice.Main.Pages.DiscountStore;

public partial class Orders
{
    [Inject] private DiscountOrderService DiscountOrderService { get; set; } = default!;

    private List<DiscountOrderSummary> _orders = new();
    private int _currentPage = 1;
    private int _totalPages;
    private bool _loading = true;
    private const int PageSize = 10;

    protected override async Task OnInitializedAsync()
    {
        await LoadOrdersAsync();
    }

    private async Task LoadOrdersAsync()
    {
        _loading = true;
        try
        {
            var result = await DiscountOrderService.GetUserOrdersAsync(_currentPage, PageSize);
            _orders = result.Orders;
            _totalPages = result.TotalPages;
        }
        catch
        {
            Snackbar.Add("خطا در بارگذاری سفارش‌ها", MudBlazor.Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task OnPageChanged(int page)
    {
        _currentPage = page;
        await LoadOrdersAsync();
    }

    private void ViewOrder(long orderId)
    {
        Navigation.NavigateTo($"{RouteConstants.DiscountStore.OrderDetail}{orderId}");
    }

    private static string FormatPrice(long price) => $"{price:N0}";

    private static string FormatDate(DateTime date)
    {
        try
        {
            return date.ToLocalTime().MiladiToJalaliWithTime();
        }
        catch
        {
            return date.ToString("yyyy/MM/dd");
        }
    }
}
