@inherits ViewModelTemplate<OrderListViewModel>
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb.Frontend
@using System.Globalization
@using System.Linq

@{
    var culturHeader = Dynamicweb.Context.Current?.Request.Headers.Get("x-dw-culture");
    var culture = !string.IsNullOrEmpty(culturHeader) ? new CultureInfo(culturHeader) : CultureInfo.CurrentCulture;
    var monthCount = 6;
    var currentMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
    var months = Enumerable.Range(0, monthCount)
        .Select(offset => currentMonth.AddMonths(offset - (monthCount - 1)))
        .ToList();

    var orders = Model?.Orders ?? Enumerable.Empty<OrderViewModel>();
    var monthlySpending = months
        .Select(monthStart =>
        {
            var monthOrders = orders
                .Where(order => order.CompletedDate != null && order.CompletedDate >= monthStart && order.CompletedDate < monthStart.AddMonths(1))
                .ToList();
            var hasMultipleCurrencies = monthOrders.Select(o => o.Price.CurrencyCode).Distinct().Count() > 1;
            return new
            {
                MonthStart = monthStart,
                Label = culture.DateTimeFormat.GetAbbreviatedMonthName(monthStart.Month),
                Value = hasMultipleCurrencies ? 0d : monthOrders.Sum(o => o.Price.Price),
                HasMultipleCurrencies = hasMultipleCurrencies,
                CurrencyCode = hasMultipleCurrencies ? null : monthOrders.Select(o => o.Price.CurrencyCode).FirstOrDefault()
            };
        })
        .ToList();

    double GetAxisUpperBound(double value)
    {
        if (value <= 0)
        {
            return 4000d;
        }

        var paddedValue = value * 1.15d;
        double roundingUnit;

        if (paddedValue <= 1000d)
        {
            roundingUnit = 100d;
        }
        else if (paddedValue <= 10000d)
        {
            roundingUnit = 500d;
        }
        else if (paddedValue <= 50000d)
        {
            roundingUnit = 1000d;
        }
        else if (paddedValue <= 100000d)
        {
            roundingUnit = 5000d;
        }
        else
        {
            roundingUnit = 10000d;
        }

        return Math.Ceiling(paddedValue / roundingUnit) * roundingUnit;
    }

    var chartCurrencyCode = monthlySpending.Select(m => m.CurrencyCode).FirstOrDefault(c => c != null) ?? "";
    var maxValue = monthlySpending.Max(month => month.Value);
    var axisUpperBound = GetAxisUpperBound(maxValue);
    var axisValues = Enumerable.Range(0, 5)
        .Select(index => axisUpperBound - ((axisUpperBound / 4d) * index))
        .ToList();
    var activeMonthIndex = monthlySpending.FindLastIndex(month => month.Value > 0);

    if (activeMonthIndex < 0)
    {
        activeMonthIndex = monthlySpending.Count - 1;
    }

    string FormatAxisLabel(double value, string currencyCode)
    {
        if (axisUpperBound >= 1000d)
        {
            var roundedThousands = Math.Round(value / 1000d, 0, MidpointRounding.AwayFromZero);
            var currency = Dynamicweb.Ecommerce.Services.Currencies?.GetCurrency(currencyCode) ?? Dynamicweb.Ecommerce.Common.Context.Currency;
            var formatted = Dynamicweb.Ecommerce.Services.Currencies?.Format(currency, roundedThousands);
            var prefix = new string(formatted?.TakeWhile(c => !char.IsDigit(c)).ToArray());
            var suffix = new string(formatted?.Reverse().TakeWhile(c => !char.IsDigit(c)).Reverse().ToArray());
            return $"{prefix}{roundedThousands:0}k{suffix}";
        }

        return Dynamicweb.Ecommerce.Services.Currencies.Format(Dynamicweb.Ecommerce.Services.Currencies?.GetCurrency(currencyCode) ?? Dynamicweb.Ecommerce.Common.Context.Currency, value);
    }

    string FormatTooltipValue(double value, string currencyCode)
    {
        return Dynamicweb.Ecommerce.Services.Currencies.Format(Dynamicweb.Ecommerce.Services.Currencies?.GetCurrency(currencyCode) ?? Dynamicweb.Ecommerce.Common.Context.Currency, value);
    }
}

@if (!orders.Any())
{
    <div class="vstack text-center fs-7 fw-semibold gap-2">
        
        <div class="d-grid rounded-circle m-auto" style="aspect-ratio:1;background-color:rgba(var(--bs-body-color-rgb), .0275);">
            <span class="icon fs-5 text-muted p-3">
                @ReadFile("/Files/Images/Icons/cube.svg")
            </span>
        </div>
        <div>@Translate("No orders found")</div>
        
    </div>
    return;
}

<div data-swift-bar-chart class="pt-3">
    <div class="chart-layout d-grid align-items-start">
        <div class="chart-axis position-relative fs-8 text-muted" aria-hidden="true">
            @for (var i = 0; i < axisValues.Count; i++)
            {
                var bottom = ((axisValues.Count - 1 - i) * 100d) / (axisValues.Count - 1);
                <span class="chart-axis-label position-absolute end-0 lh-1 text-nowrap" style="bottom: @(bottom.ToString("0.##", CultureInfo.InvariantCulture))%;">
                    @(FormatAxisLabel(axisValues[i], chartCurrencyCode))
                </span>
            }
        </div>
        <div class="chart-plot position-relative" role="img" aria-label="@(Translate("Monthly spending for the last six months"))">
            @for (var i = 0; i < axisValues.Count; i++)
            {
                var bottom = ((axisValues.Count - 1 - i) * 100d) / (axisValues.Count - 1);
                <span class="chart-grid-line position-absolute start-0 end-0 z-0" aria-hidden="true" style="bottom: @(bottom.ToString("0.##", CultureInfo.InvariantCulture))%;"></span>
            }

            <div class="chart-bars position-relative z-1 h-100 d-grid">
                @for (var i = 0; i < monthlySpending.Count; i++)
                {
                    var month = monthlySpending[i];
                    var barHeight = axisUpperBound > 0 ? (month.Value / axisUpperBound) * 100d : 0d;

                    <button type="button"
                        class="chart-column d-grid gap-2 align-items-end p-0 bg-transparent border-0"
                        style="--swift-chart-bar-height: @(barHeight.ToString("0.##", CultureInfo.InvariantCulture));"
                        aria-label="@(month.MonthStart.ToString("Y", culture)): @(month.HasMultipleCurrencies ? Translate("Cannot display total in multiple currencies") : FormatTooltipValue(month.Value, month.CurrencyCode ?? chartCurrencyCode))">
                        <span class="chart-track position-relative d-flex align-items-end justify-content-center h-100">
                            <span class="chart-highlight position-absolute" aria-hidden="true"></span>
                            <span class="chart-value-tooltip position-absolute start-50 pe-none text-nowrap z-1 card p-2 bg-body fs-8 text-start shadow-sm" role="tooltip">
                                <span class="d-block mb-1 fw-bold text-capitalize">@(month.Label)</span>
                                @if (month.HasMultipleCurrencies)
                                {
                                    <span>@(Translate("Cannot display total in multiple currencies"))</span>
                                }
                                else
                                {
                                    <span>@(FormatTooltipValue(month.Value, month.CurrencyCode ?? chartCurrencyCode))</span>
                                }
                            </span>
                            <span class="chart-bar position-relative" aria-hidden="true"></span>
                        </span>
                        <span class="text-muted text-capitalize fs-8 text-center">@(month.Label)</span>
                    </button>
                }
            </div>
        </div>
    </div>
</div>
