@page "/admin/reports/revenue"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject ISnackbar Snackbar
@using WebClientTpos.Client.Services

@*
    EN: Revenue Analytics Dashboard — trends, payment methods, top products, vertical breakdown.
    VI: Trang phan tich doanh thu — xu huong, phuong thuc thanh toan, san pham ban chay, phan tich nganh.
*@

<PageTitle>Phan tich doanh thu — aPOS POS</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Phan tich doanh thu</h1>
        <p class="admin-topbar__subtitle">Xu huong doanh thu, phuong thuc thanh toan va san pham ban chay</p>
    </div>
    <div class="admin-topbar__right" style="display:flex;align-items:center;gap:12px;">
        <MudDateRangePicker @bind-DateRange="_dateRange"
                            Label="Khoang thoi gian"
                            Variant="Variant.Outlined"
                            DateFormat="dd/MM/yyyy"
                            MaxDate="DateTime.Today"
                            Style="max-width:280px;"
                            Color="Color.Primary"
                            Class="mud-input-dark" />
        <MudChipSet T="string" @bind-SelectedValue="_selectedPeriod" Mandatory="true" Class="ml-2">
            <MudChip T="string" Value="@("daily")" Color="Color.Primary" Variant="Variant.Text">Ngay</MudChip>
            <MudChip T="string" Value="@("weekly")" Color="Color.Primary" Variant="Variant.Text">Tuan</MudChip>
            <MudChip T="string" Value="@("monthly")" Color="Color.Primary" Variant="Variant.Text">Thang</MudChip>
        </MudChipSet>
        <MudButton Variant="Variant.Filled"
                   Color="Color.Primary"
                   OnClick="LoadDataAsync"
                   Disabled="_loading"
                   StartIcon="@Icons.Material.Filled.Analytics">
            @if (_loading)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Surface" Class="mr-2" />
            }
            Xem phan tich
        </MudButton>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="admin-content" style="display:flex;flex-direction:column;gap:20px;">

    @if (_loading)
    {
        <div style="display:flex;justify-content:center;padding:48px;">
            <MudProgressCircular Size="Size.Large" Indeterminate="true" Color="Color.Primary" />
        </div>
    }
    else if (_data == null)
    {
        <MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
            Chon khoang thoi gian va nhan "Xem phan tich" de tai du lieu doanh thu.
        </MudAlert>
    }
    else
    {
        @* ── KPI SUMMARY CARDS ── *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;">
            @* Total Revenue *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);">
                    <i data-lucide="trending-up" style="color:#22C55E;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@FormatVND(_data.TotalRevenue)</span>
                    <span class="admin-stat-card__label">Tong doanh thu</span>
                    @if (_data.PreviousPeriodRevenue > 0)
                    {
                        <span style="font-size:11px;color:var(--admin-text-tertiary);">Ky truoc: @FormatVND(_data.PreviousPeriodRevenue)</span>
                    }
                </div>
            </div>
            @* Total Orders *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);">
                    <i data-lucide="shopping-bag" style="color:#3B82F6;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_data.TotalOrders</span>
                    <span class="admin-stat-card__label">Tong don hang</span>
                </div>
            </div>
            @* Average Order Value *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(139,92,246,0.1);">
                    <i data-lucide="banknote" style="color:#8B5CF6;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@FormatVND(_data.AverageOrderValue)</span>
                    <span class="admin-stat-card__label">Gia tri TB / don</span>
                </div>
            </div>
            @* Growth % *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:@(_data.GrowthPercentage >= 0 ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");">
                    <i data-lucide="@(_data.GrowthPercentage >= 0 ? "arrow-up-right" : "arrow-down-right")"
                       style="color:@(_data.GrowthPercentage >= 0 ? "#22C55E" : "#EF4444");"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value" style="color:@(_data.GrowthPercentage >= 0 ? "#22C55E" : "#EF4444");">
                        @(_data.GrowthPercentage >= 0 ? "+" : "")@_data.GrowthPercentage.ToString("N1")%
                    </span>
                    <span class="admin-stat-card__label">Tang truong so voi ky truoc</span>
                </div>
            </div>
        </div>

        @* ── REVENUE TREND CHART ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">Xu huong doanh thu</h3>
            </div>
            <div class="admin-panel__body">
                @if (_trendChartSeries.Any())
                {
                    <MudChart ChartType="ChartType.Line"
                              ChartSeries="@_trendChartSeries"
                              XAxisLabels="@_trendChartLabels"
                              Width="100%"
                              Height="350px"
                              ChartOptions="_lineOptions" />
                }
                else
                {
                    <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu xu huong.</div>
                }
            </div>
        </div>

        @* ── PAYMENT METHODS & VERTICAL BREAKDOWN ── *@
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
            @* Payment Method Donut *@
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">Phuong thuc thanh toan</h3>
                </div>
                <div class="admin-panel__body">
                    @if (_data.PaymentMethods.Any())
                    {
                        <div style="display:flex;gap:24px;align-items:center;">
                            <div style="flex:1;">
                                <MudChart ChartType="ChartType.Donut"
                                          InputData="@_paymentChartData"
                                          InputLabels="@_paymentChartLabels"
                                          Width="220px"
                                          Height="220px"
                                          ChartOptions="_donutOptions" />
                            </div>
                            <div style="flex:1;">
                                @foreach (var p in _data.PaymentMethods)
                                {
                                    <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--admin-border-subtle);">
                                        <div>
                                            <span style="font-weight:600;color:var(--admin-text-primary);">@GetPaymentMethodLabel(p.Method)</span>
                                            <span style="font-size:12px;color:var(--admin-text-tertiary);margin-left:8px;">@p.Percentage%</span>
                                        </div>
                                        <span style="font-weight:700;color:var(--admin-orange-primary);">@FormatVND(p.Amount)</span>
                                    </div>
                                }
                            </div>
                        </div>
                    }
                    else
                    {
                        <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu thanh toan.</div>
                    }
                </div>
            </div>

            @* Vertical Revenue Bar Chart *@
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">Doanh thu theo nganh</h3>
                </div>
                <div class="admin-panel__body">
                    @if (_verticalChartSeries.Any())
                    {
                        <MudChart ChartType="ChartType.Bar"
                                  ChartSeries="@_verticalChartSeries"
                                  XAxisLabels="@_verticalChartLabels"
                                  Width="100%"
                                  Height="300px"
                                  ChartOptions="_barOptions" />
                    }
                    else
                    {
                        <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu nganh.</div>
                    }
                </div>
            </div>
        </div>

        @* ── ORDER COUNT DISTRIBUTION ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">Phan bo don hang theo thoi gian</h3>
            </div>
            <div class="admin-panel__body">
                @if (_orderCountChartSeries.Any())
                {
                    <MudChart ChartType="ChartType.Bar"
                              ChartSeries="@_orderCountChartSeries"
                              XAxisLabels="@_trendChartLabels"
                              Width="100%"
                              Height="280px"
                              ChartOptions="_orderCountBarOptions" />
                }
                else
                {
                    <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu phan bo don hang.</div>
                }
            </div>
        </div>

        @* ── TOP 10 PRODUCTS TABLE ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">Top 10 san pham ban chay</h3>
            </div>
            <div class="admin-panel__body" style="padding:0;">
                @if (_data.TopProducts.Any())
                {
                    <MudTable Items="@_data.TopProducts"
                              Dense="true"
                              Hover="true"
                              Striped="true"
                              Elevation="0"
                              Class="mud-table-dark">
                        <HeaderContent>
                            <MudTh Style="font-weight:700;">#</MudTh>
                            <MudTh Style="font-weight:700;">Ten san pham</MudTh>
                            <MudTh Style="font-weight:700;text-align:right;">So luong ban</MudTh>
                            <MudTh Style="font-weight:700;text-align:right;">Doanh thu</MudTh>
                        </HeaderContent>
                        <RowTemplate>
                            <MudTd Style="font-weight:700;color:var(--admin-orange-primary);">@(_data.TopProducts.IndexOf(context) + 1)</MudTd>
                            <MudTd Style="font-weight:600;">@context.Name</MudTd>
                            <MudTd Style="text-align:right;font-weight:600;color:#3B82F6;">@context.QuantitySold</MudTd>
                            <MudTd Style="text-align:right;font-weight:700;color:var(--admin-orange-primary);">@FormatVND(context.Revenue)</MudTd>
                        </RowTemplate>
                    </MudTable>
                }
                else
                {
                    <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu san pham.</div>
                }
            </div>
        </div>
    }
</div>

@code {
    // EN: Date range for the report / VI: Khoang thoi gian cho bao cao
    private DateRange _dateRange = new(DateTime.Today.AddDays(-30), DateTime.Today);
    private string _selectedPeriod = "daily";
    private bool _loading = false;
    private PosDataService.RevenueAnalyticsInfo? _data;

    // EN: Chart data arrays / VI: Mang du lieu bieu do
    private List<ChartSeries> _trendChartSeries = new();
    private string[] _trendChartLabels = Array.Empty<string>();
    private double[] _paymentChartData = Array.Empty<double>();
    private string[] _paymentChartLabels = Array.Empty<string>();
    private List<ChartSeries> _verticalChartSeries = new();
    private string[] _verticalChartLabels = Array.Empty<string>();
    private List<ChartSeries> _orderCountChartSeries = new();

    private ChartOptions _lineOptions = new()
    {
        ChartPalette = new[] { "#FF5C00", "#3B82F6" },
        YAxisTicks = 5,
        LineStrokeWidth = 2.5
    };

    private ChartOptions _donutOptions = new()
    {
        ChartPalette = new[] { "#22C55E", "#3B82F6", "#8B5CF6", "#F59E0B", "#EC4899", "#FF5C00" }
    };

    private ChartOptions _barOptions = new()
    {
        ChartPalette = new[] { "#FF5C00", "#3B82F6", "#22C55E", "#8B5CF6", "#F59E0B" },
        YAxisTicks = 5
    };

    private ChartOptions _orderCountBarOptions = new()
    {
        ChartPalette = new[] { "#3B82F6" },
        YAxisTicks = 5
    };

    /// <summary>
    /// EN: Get the current shop ID from query string context.
    /// VI: Lay shop ID hien tai tu query string context.
    /// </summary>
    private Guid? GetCurrentShopId()
    {
        var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
        if (Guid.TryParse(query["shopId"], out var qsShopId))
            return qsShopId;
        return null;
    }

    /// <summary>
    /// EN: Load revenue analytics data.
    /// VI: Tai du lieu phan tich doanh thu.
    /// </summary>
    private async Task LoadDataAsync()
    {
        var shopId = GetCurrentShopId();
        if (!shopId.HasValue)
        {
            Snackbar.Add("Vui long chon shop truoc khi xem bao cao.", Severity.Warning);
            return;
        }

        if (_dateRange.Start == null || _dateRange.End == null)
        {
            Snackbar.Add("Vui long chon khoang thoi gian.", Severity.Warning);
            return;
        }

        _loading = true;
        _data = null;
        StateHasChanged();

        try
        {
            _data = await DataService.GetRevenueAnalyticsAsync(
                shopId.Value,
                _dateRange.Start.Value,
                _dateRange.End.Value,
                _selectedPeriod);

            if (_data != null)
            {
                BuildChartData();
                Snackbar.Add("Da tai phan tich doanh thu thanh cong.", Severity.Success);
            }
            else
            {
                Snackbar.Add("Khong the tai du lieu. Vui long thu lai.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Build chart data arrays from analytics data.
    /// VI: Xay dung mang du lieu bieu do tu du lieu phan tich.
    /// </summary>
    private void BuildChartData()
    {
        if (_data == null) return;

        // EN: Revenue trend line chart / VI: Bieu do duong xu huong doanh thu
        if (_data.Trends.Any())
        {
            _trendChartLabels = _data.Trends.Select(t => FormatTrendLabel(t.Date)).ToArray();
            _trendChartSeries = new List<ChartSeries>
            {
                new ChartSeries { Name = "Doanh thu", Data = _data.Trends.Select(t => (double)t.Revenue).ToArray() }
            };
            _orderCountChartSeries = new List<ChartSeries>
            {
                new ChartSeries { Name = "So don hang", Data = _data.Trends.Select(t => (double)t.OrderCount).ToArray() }
            };
        }
        else
        {
            _trendChartLabels = Array.Empty<string>();
            _trendChartSeries = new();
            _orderCountChartSeries = new();
        }

        // EN: Payment method donut chart / VI: Bieu do tron phuong thuc thanh toan
        if (_data.PaymentMethods.Any())
        {
            _paymentChartData = _data.PaymentMethods.Select(p => (double)p.Amount).ToArray();
            _paymentChartLabels = _data.PaymentMethods.Select(p => GetPaymentMethodLabel(p.Method)).ToArray();
        }
        else
        {
            _paymentChartData = Array.Empty<double>();
            _paymentChartLabels = Array.Empty<string>();
        }

        // EN: Vertical breakdown bar chart / VI: Bieu do cot phan tich nganh
        if (_data.VerticalBreakdown.Any())
        {
            _verticalChartLabels = _data.VerticalBreakdown.Select(v => GetVerticalLabel(v.Vertical)).ToArray();
            _verticalChartSeries = new List<ChartSeries>
            {
                new ChartSeries { Name = "Doanh thu", Data = _data.VerticalBreakdown.Select(v => (double)v.Revenue).ToArray() }
            };
        }
        else
        {
            _verticalChartLabels = Array.Empty<string>();
            _verticalChartSeries = new();
        }
    }

    /// <summary>
    /// EN: Format trend date label based on selected period.
    /// VI: Dinh dang nhan ngay xu huong theo ky da chon.
    /// </summary>
    private string FormatTrendLabel(DateTime date) => _selectedPeriod switch
    {
        "monthly" => date.ToString("MM/yyyy"),
        "weekly" => $"T{System.Globalization.ISOWeek.GetWeekOfYear(date)} {date:yyyy}",
        _ => date.ToString("dd/MM")
    };

    /// <summary>
    /// EN: Get Vietnamese label for payment method.
    /// VI: Lay nhan tieng Viet cho phuong thuc thanh toan.
    /// </summary>
    private static string GetPaymentMethodLabel(string method) => method.ToLowerInvariant() switch
    {
        "cash" => "Tien mat",
        "card" => "The",
        "vnpay" => "VNPay",
        "momo" => "MoMo",
        "qr" => "QR Code",
        "transfer" => "Chuyen khoan",
        "unknown" => "Chua xac dinh",
        _ => method
    };

    /// <summary>
    /// EN: Get Vietnamese label for business vertical.
    /// VI: Lay nhan tieng Viet cho nganh kinh doanh.
    /// </summary>
    private static string GetVerticalLabel(string vertical) => vertical.ToLowerInvariant() switch
    {
        "karaoke" => "Karaoke",
        "restaurant" => "Nha hang",
        "cafe" => "Cafe",
        "spa" => "Spa",
        "retail" => "Ban le",
        "other" => "Khac",
        _ => vertical
    };

    private static string FormatVND(decimal val) => val.ToString("N0") + " d";
}
