@page "/admin/reports/eod"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject IDialogService DialogService
@inject ISnackbar Snackbar
@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop

@*
    EN: End-of-Day Report page — daily closing summary with revenue, orders, payment breakdown, and top items.
    VI: Trang bao cao cuoi ngay — tom tat dong ngay voi doanh thu, don hang, phan tich thanh toan, va san pham ban chay.
*@

<PageTitle>Bao cao cuoi ngay — aPOS POS</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Bao cao cuoi ngay</h1>
        <p class="admin-topbar__subtitle">Tong hop doanh thu va don hang trong ngay</p>
    </div>
    <div class="admin-topbar__right" style="display:flex;align-items:center;gap:12px;">
        <MudDatePicker @bind-Date="_selectedDate"
                       Label="Chon ngay"
                       Variant="Variant.Outlined"
                       DateFormat="dd/MM/yyyy"
                       MaxDate="DateTime.Today"
                       Style="max-width:180px;"
                       Color="Color.Primary"
                       Class="mud-input-dark" />
        <MudButton Variant="Variant.Filled"
                   Color="Color.Primary"
                   OnClick="LoadReportAsync"
                   Disabled="_loading"
                   StartIcon="@Icons.Material.Filled.Assessment">
            @if (_loading)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Surface" Class="mr-2" />
            }
            Xem bao cao
        </MudButton>
        <MudButton Variant="Variant.Outlined"
                   Color="Color.Warning"
                   OnClick="CloseDayAsync"
                   Disabled="_loading || _report == null"
                   StartIcon="@Icons.Material.Filled.Lock">
            Dong ngay
        </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 (_report == null)
    {
        <MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
            Chon ngay va nhan "Xem bao cao" de tai du lieu bao cao cuoi ngay.
        </MudAlert>
    }
    else
    {
        @* ── KPI SUMMARY CARDS ── *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,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(_report.TotalRevenue)</span>
                    <span class="admin-stat-card__label">Tong doanh thu</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">@_report.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(_report.TotalOrders > 0 ? _report.TotalRevenue / _report.TotalOrders : 0)</span>
                    <span class="admin-stat-card__label">Gia tri TB / don</span>
                </div>
            </div>
            @* Discount Total *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(236,72,153,0.1);">
                    <i data-lucide="percent" style="color:#EC4899;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@FormatVND(_report.DiscountTotal)</span>
                    <span class="admin-stat-card__label">Giam gia</span>
                </div>
            </div>
            @* Completed Orders *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);">
                    <i data-lucide="check-circle" style="color:#22C55E;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_report.CompletedOrders</span>
                    <span class="admin-stat-card__label">Hoan thanh</span>
                </div>
            </div>
            @* Cancelled Orders *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(239,68,68,0.1);">
                    <i data-lucide="x-circle" style="color:#EF4444;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_report.CancelledOrders</span>
                    <span class="admin-stat-card__label">Da huy</span>
                </div>
            </div>
        </div>

        @* ── REVENUE BY PAYMENT METHOD ── *@
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
            @* Payment Breakdown Chart *@
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">Phan tich thanh toan</h3>
                </div>
                <div class="admin-panel__body">
                    @if (_report.PaymentBreakdown.Any())
                    {
                        <div style="display:flex;gap:24px;align-items:center;">
                            <div style="flex:1;">
                                <MudChart ChartType="ChartType.Donut"
                                          InputData="@_paymentChartData"
                                          InputLabels="@_paymentChartLabels"
                                          Width="200px"
                                          Height="200px"
                                          ChartOptions="_donutOptions" />
                            </div>
                            <div style="flex:1;">
                                @foreach (var p in _report.PaymentBreakdown)
                                {
                                    <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.Count don)</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>

            @* Revenue Breakdown Cards *@
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">Doanh thu theo loai</h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:12px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:12px;border-radius:8px;background:rgba(34,197,94,0.08);">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <i data-lucide="banknote" style="color:#22C55E;width:20px;height:20px;"></i>
                            <span style="font-weight:600;">Tien mat</span>
                        </div>
                        <span style="font-weight:700;color:#22C55E;">@FormatVND(_report.CashRevenue)</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:12px;border-radius:8px;background:rgba(59,130,246,0.08);">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <i data-lucide="credit-card" style="color:#3B82F6;width:20px;height:20px;"></i>
                            <span style="font-weight:600;">The</span>
                        </div>
                        <span style="font-weight:700;color:#3B82F6;">@FormatVND(_report.CardRevenue)</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:12px;border-radius:8px;background:rgba(139,92,246,0.08);">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <i data-lucide="smartphone" style="color:#8B5CF6;width:20px;height:20px;"></i>
                            <span style="font-weight:600;">Truc tuyen</span>
                        </div>
                        <span style="font-weight:700;color:#8B5CF6;">@FormatVND(_report.OnlineRevenue)</span>
                    </div>
                </div>
            </div>
        </div>

        @* ── HOURLY REVENUE CHART ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">Doanh thu theo gio</h3>
            </div>
            <div class="admin-panel__body">
                @if (_hourlyChartData.Length > 0)
                {
                    <MudChart ChartType="ChartType.Bar"
                              ChartSeries="@_hourlyChartSeries"
                              XAxisLabels="@_hourlyChartLabels"
                              Width="100%"
                              Height="300px"
                              ChartOptions="_barOptions" />
                }
                else
                {
                    <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu doanh thu theo gio.</div>
                }
            </div>
        </div>

        @* ── TOP 10 ITEMS 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 (_report.TopItems.Any())
                {
                    <MudTable Items="@_report.TopItems"
                              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</MudTh>
                            <MudTh Style="font-weight:700;text-align:right;">Doanh thu</MudTh>
                        </HeaderContent>
                        <RowTemplate>
                            <MudTd Style="font-weight:700;color:var(--admin-orange-primary);">@((_report.TopItems.IndexOf(context) + 1))</MudTd>
                            <MudTd Style="font-weight:600;">@context.ItemName</MudTd>
                            <MudTd Style="text-align:right;font-weight:600;color:#3B82F6;">@context.Quantity</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: Selected date for the report / VI: Ngay duoc chon cho bao cao
    private DateTime? _selectedDate = DateTime.Today;
    private bool _loading = false;
    private PosDataService.EodReportInfo? _report;

    // EN: Chart data arrays / VI: Mang du lieu bieu do
    private double[] _paymentChartData = Array.Empty<double>();
    private string[] _paymentChartLabels = Array.Empty<string>();
    private double[] _hourlyChartData = Array.Empty<double>();
    private string[] _hourlyChartLabels = Array.Empty<string>();
    private List<ChartSeries> _hourlyChartSeries = new();

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

    private ChartOptions _barOptions = new()
    {
        ChartPalette = new[] { "#FF5C00" },
        YAxisTicks = 5
    };

    /// <summary>
    /// EN: Get the current shop ID from the admin context.
    /// VI: Lay shop ID hien tai tu admin context.
    /// </summary>
    private Guid? GetCurrentShopId()
    {
        // EN: Try to get shop ID from query string or AuthStateService context
        // VI: Thu lay shop ID tu query string hoac AuthStateService context
        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 the EOD report for the selected date.
    /// VI: Tai bao cao cuoi ngay cho ngay duoc chon.
    /// </summary>
    private async Task LoadReportAsync()
    {
        var shopId = GetCurrentShopId();
        if (!shopId.HasValue)
        {
            Snackbar.Add("Vui long chon shop truoc khi xem bao cao.", Severity.Warning);
            return;
        }

        if (!_selectedDate.HasValue)
        {
            Snackbar.Add("Vui long chon ngay bao cao.", Severity.Warning);
            return;
        }

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

        try
        {
            _report = await DataService.GetEodReportAsync(shopId.Value, _selectedDate.Value);
            if (_report != null)
            {
                BuildChartData();
                Snackbar.Add($"Da tai bao cao ngay {_selectedDate.Value:dd/MM/yyyy}.", Severity.Success);
            }
            else
            {
                Snackbar.Add("Khong the tai bao cao. Vui long thu lai.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Close the business day with confirmation dialog.
    /// VI: Dong ngay kinh doanh voi dialog xac nhan.
    /// </summary>
    private async Task CloseDayAsync()
    {
        var shopId = GetCurrentShopId();
        if (!shopId.HasValue || !_selectedDate.HasValue) return;

        var confirmed = await DialogService.ShowMessageBox(
            "Xac nhan dong ngay",
            $"Ban co chac chan muon dong ngay {_selectedDate.Value:dd/MM/yyyy}? Hanh dong nay se tao bao cao cuoi ngay chinh thuc.",
            yesText: "Dong ngay",
            cancelText: "Huy");

        if (confirmed != true) return;

        _loading = true;
        StateHasChanged();

        try
        {
            var result = await DataService.CloseDayAsync(shopId.Value, _selectedDate.Value);
            if (result != null && result.Success)
            {
                if (result.Report != null)
                {
                    _report = result.Report;
                    BuildChartData();
                }

                var message = $"Da dong ngay {_selectedDate.Value:dd/MM/yyyy} thanh cong.";
                if (result.PendingOrderCount > 0)
                {
                    message += $" Luu y: {result.PendingOrderCount} don hang van dang cho xu ly.";
                    Snackbar.Add(message, Severity.Warning);
                }
                else
                {
                    Snackbar.Add(message, Severity.Success);
                }
            }
            else
            {
                Snackbar.Add(result?.Message ?? "Khong the dong ngay. 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 the report.
    /// VI: Xay dung mang du lieu bieu do tu bao cao.
    /// </summary>
    private void BuildChartData()
    {
        if (_report == null) return;

        // EN: Payment breakdown donut chart / VI: Bieu do tron phan tich thanh toan
        if (_report.PaymentBreakdown.Any())
        {
            _paymentChartData = _report.PaymentBreakdown.Select(p => (double)p.Amount).ToArray();
            _paymentChartLabels = _report.PaymentBreakdown.Select(p => GetPaymentMethodLabel(p.Method)).ToArray();
        }
        else
        {
            _paymentChartData = Array.Empty<double>();
            _paymentChartLabels = Array.Empty<string>();
        }

        // EN: Hourly revenue bar chart / VI: Bieu do cot doanh thu theo gio
        if (_report.HourlyRevenue.Any())
        {
            _hourlyChartData = _report.HourlyRevenue.Select(h => (double)h.Revenue).ToArray();
            _hourlyChartLabels = _report.HourlyRevenue.Select(h => $"{h.Hour:00}:00").ToArray();
            _hourlyChartSeries = new List<ChartSeries>
            {
                new ChartSeries { Name = "Doanh thu", Data = _hourlyChartData }
            };
        }
        else
        {
            _hourlyChartData = Array.Empty<double>();
            _hourlyChartLabels = Array.Empty<string>();
            _hourlyChartSeries = new();
        }
    }

    /// <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
    };

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