@*
    EN: Daily Report — End-of-day summary: revenue, orders, popular items, payment breakdown.
        Connected to POS dashboard API for real-time data.
    VI: Báo cáo ngày — Tổng kết cuối ngày: doanh thu, đơn hàng, món phổ biến, phân tích thanh toán.
        Kết nối API POS dashboard cho dữ liệu thời gian thực.
*@
@page "/pos/{ShopId:guid}/cafe/daily-report"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div style="padding:24px;overflow-y:auto;height:100%;">
    @* EN: Header / VI: Tiêu đề *@
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;">
        <div>
            <h2 style="font-size:22px;font-weight:700;margin:0;">Báo cáo ngày</h2>
            <span style="font-size:13px;color:var(--pos-text-tertiary);">@DateTime.Now.ToString("dd/MM/yyyy") — Ca sáng</span>
        </div>
        <button style="padding:10px 20px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);background:transparent;color:var(--pos-text-primary);font-size:13px;cursor:pointer;">
            <i data-lucide="download" style="width:14px;height:14px;vertical-align:middle;margin-right:4px;"></i>
            Xuất PDF
        </button>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;padding:60px 0;color:var(--pos-text-tertiary);">
            <div style="font-size:14px;">Đang tải báo cáo...</div>
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:60px 0;color:var(--pos-text-tertiary);">
            <div style="font-size:14px;margin-bottom:12px;">Không thể tải dữ liệu báo cáo</div>
            <button style="padding:8px 16px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:13px;" @onclick="LoadReportAsync">Thử lại</button>
        </div>
    }
    else
    {
    @* EN: Summary cards / VI: Thẻ tổng quan *@
    <div style="display:grid;grid-template-columns:repeat(4, 1fr);gap:16px;margin-bottom:24px;">
        @foreach (var stat in _stats)
        {
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:8px;">@stat.Label</div>
                <div style="font-size:24px;font-weight:700;color:@stat.Color;">@stat.Value</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:4px;">@stat.Sub</div>
            </div>
        }
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        @* EN: Popular items / VI: Món phổ biến *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
            <h3 style="font-size:15px;font-weight:600;margin:0 0 16px;">Món bán chạy</h3>
            @if (_popularItems.Any())
            {
                @foreach (var item in _popularItems)
                {
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--pos-border-subtle);">
                        <div>
                            <div style="font-size:14px;font-weight:500;">@item.Name</div>
                            <div style="font-size:12px;color:var(--pos-text-tertiary);">@item.Qty đã bán</div>
                        </div>
                        <span style="font-size:14px;font-weight:600;color:var(--pos-orange-primary);">@FormatPrice(item.Revenue)</span>
                    </div>
                }
            }
            else
            {
                <div style="font-size:13px;color:var(--pos-text-tertiary);padding:16px 0;">Chưa có dữ liệu</div>
            }
        </div>

        @* EN: Payment breakdown / VI: Phân tích thanh toán *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
            <h3 style="font-size:15px;font-weight:600;margin:0 0 16px;">Hình thức thanh toán</h3>
            @if (_payments.Any())
            {
                @foreach (var payment in _payments)
                {
                    <div style="margin-bottom:16px;">
                        <div style="display:flex;justify-content:space-between;margin-bottom:6px;">
                            <span style="font-size:13px;">@payment.Method</span>
                            <span style="font-size:13px;font-weight:600;">@FormatPrice(payment.Amount)</span>
                        </div>
                        <div style="height:6px;border-radius:3px;background:var(--pos-bg-interactive);">
                            <div style="height:100%;border-radius:3px;background:var(--pos-orange-primary);width:@(payment.Pct)%;"></div>
                        </div>
                    </div>
                }
            }
            else
            {
                <div style="font-size:13px;color:var(--pos-text-tertiary);padding:16px 0;">Chưa có dữ liệu</div>
            }

            @* EN: Hourly chart / VI: Biểu đồ theo giờ *@
            <h3 style="font-size:15px;font-weight:600;margin:24px 0 16px;">Doanh thu theo giờ</h3>
            @if (_hourlyData.Any())
            {
                <div style="display:flex;align-items:flex-end;gap:6px;height:120px;">
                    @foreach (var h in _hourlyData)
                    {
                        <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;">
                            <div style="width:100%;background:var(--pos-orange-primary);border-radius:4px 4px 0 0;height:@(h.Pct)%;opacity:@(h.Pct > 0 ? 1 : 0.3);"></div>
                            <span style="font-size:9px;color:var(--pos-text-tertiary);">@h.HourLabel</span>
                        </div>
                    }
                </div>
            }
            else
            {
                <div style="font-size:13px;color:var(--pos-text-tertiary);padding:16px 0;">Chưa có dữ liệu</div>
            }
        </div>
    </div>
    }
</div>

@code {
    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Dashboard data from API / VI: Dữ liệu dashboard từ API
    private List<StatCard> _stats = new();
    private List<PosDataService.PopularItemInfo> _popularItems = new();
    private List<PosDataService.PaymentBreakdownInfo> _payments = new();
    private List<PosDataService.HourlyRevenueInfo> _hourlyData = new();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadReportAsync();
    }

    private async Task LoadReportAsync()
    {
        _isLoading = true;
        _loadError = false;
        StateHasChanged();

        try
        {
            // EN: Fetch dashboard data for today / VI: Lấy dữ liệu dashboard cho hôm nay
            var data = await DataService.GetPosDashboardAsync(ShopId, "today");

            // EN: Build summary stat cards from API data / VI: Tạo thẻ thống kê từ dữ liệu API
            _stats = new List<StatCard>
            {
                new("Doanh thu", FormatPrice(data.Revenue), "var(--pos-orange-primary)",
                    data.AvgOrderValue > 0 ? $"TB {FormatPrice(data.AvgOrderValue)}/đơn" : "—"),
                new("Đơn hàng", data.OrderCount.ToString("N0"), "var(--pos-success)",
                    data.OrderCount > 0 ? $"TB {FormatPrice(data.AvgOrderValue)}/đơn" : "—"),
                new("Món bán ra", data.ItemsSold.ToString("N0"), "var(--pos-warning)",
                    data.OrderCount > 0 ? $"{(double)data.ItemsSold / data.OrderCount:F1} món/đơn" : "—"),
                new("Đơn trung bình", FormatPrice(data.AvgOrderValue), "var(--pos-info)", "Giá trị trung bình"),
            };

            _popularItems = data.PopularItems ?? new();

            // EN: Compute percentage for payment breakdown / VI: Tính phần trăm cho breakdown thanh toán
            _payments = data.PaymentBreakdown ?? new();
            var totalPayments = _payments.Sum(p => p.Amount);
            foreach (var p in _payments)
                p.Pct = totalPayments > 0 ? (int)(p.Amount / totalPayments * 100) : 0;

            // EN: Compute percentage for hourly revenue (relative to max) / VI: Tính % doanh thu theo giờ (tương đối so với max)
            _hourlyData = data.HourlyRevenue ?? new();
            var maxHourly = _hourlyData.Any() ? _hourlyData.Max(h => h.Revenue) : 0;
            foreach (var h in _hourlyData)
                h.Pct = maxHourly > 0 ? (int)(h.Revenue / maxHourly * 100) : 0;
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private record StatCard(string Label, string Value, string Color, string Sub);
}
