@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService
@inject IJSRuntime JS

@* ─── Date Range Filter ─── *@
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:12px;">
    <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
        <div style="display:flex;align-items:center;gap:6px;">
            <label style="font-size:12px;font-weight:600;color:var(--admin-text-tertiary);">Từ</label>
            <input type="date" value="@_startDate.ToString("yyyy-MM-dd")" @onchange="OnStartDateChanged"
                style="padding:6px 10px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" />
        </div>
        <div style="display:flex;align-items:center;gap:6px;">
            <label style="font-size:12px;font-weight:600;color:var(--admin-text-tertiary);">Đến</label>
            <input type="date" value="@_endDate.ToString("yyyy-MM-dd")" @onchange="OnEndDateChanged"
                style="padding:6px 10px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" />
        </div>
        <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
            @foreach (var (label, days) in new[] { ("7 ngày", 7), ("30 ngày", 30), ("90 ngày", 90), ("Tất cả", 0) })
            {
                <button @onclick="@(() => SetDateRange(days))"
                    style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;border:none;
                        background:@(_activeDateRange == days ? "var(--admin-orange-primary)" : "transparent");
                        color:@(_activeDateRange == days ? "#FFF" : "var(--admin-text-tertiary)");">
                    @label
                </button>
            }
        </div>
    </div>
    <button @onclick="ExportCsv" style="padding:6px 14px;border-radius:8px;border:1px solid rgba(34,197,94,0.3);background:rgba(34,197,94,0.1);color:#22C55E;font-size:12px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:6px;">
        <i data-lucide="download" style="width:14px;height:14px;"></i> Xuất CSV
    </button>
</div>

@* ─── KPI Summary Cards ─── *@
@{
    var filteredOrders = GetFilteredOrders();
    var totalRevenue = filteredOrders.Sum(o => o.TotalAmount);
    var totalOrders = filteredOrders.Count;
    var avgOrderValue = totalOrders > 0 ? filteredOrders.Average(o => o.TotalAmount) : 0m;
}
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-bottom:20px;">
    <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">@ShopHelpers.FormatVND(totalRevenue)</span><span class="admin-stat-card__label">Tổng doanh thu</span></div></div>
    <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">@totalOrders</span><span class="admin-stat-card__label">Tổng đơn hàng</span></div></div>
    <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">@ShopHelpers.FormatVND(avgOrderValue)</span><span class="admin-stat-card__label">Giá trị TB / đơn</span></div></div>
    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(236,72,153,0.1);"><i data-lucide="package" style="color:#EC4899;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_reportProducts.Count</span><span class="admin-stat-card__label">Sản phẩm</span></div></div>
</div>

@* ─── Revenue Report ─── *@
<div class="admin-panel" style="margin-bottom:16px;">
    <div class="admin-panel__header">
        <h3 class="admin-panel__title">Doanh thu theo kỳ</h3>
        <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
            @foreach (var (label, val) in new[] { ("Ngày", "daily"), ("Tuần", "weekly"), ("Tháng", "monthly") })
            {
                <button @onclick="@(() => LoadRevenueReport(val))"
                    style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;border:none;
                        background:@(_reportPeriod == val ? "var(--admin-orange-primary)" : "transparent");
                        color:@(_reportPeriod == val ? "#FFF" : "var(--admin-text-tertiary)");">
                    @label
                </button>
            }
        </div>
    </div>
    <div class="admin-panel__body" style="padding:0;">
        @if (_loadingRevenue)
        {
            <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);font-size:14px;">
                <i data-lucide="loader-2" style="width:20px;height:20px;animation:spin 1s linear infinite;"></i>
                Đang tải...
            </div>
        }
        else if (_revenueReport.Any())
        {
            <table style="width:100%;border-collapse:collapse;">
                <thead><tr style="font-size:12px;color:var(--admin-text-tertiary);text-align:left;border-bottom:1px solid var(--admin-border-subtle);">
                    <th style="padding:10px 16px;">KỲ</th><th style="padding:10px 16px;text-align:right;">ĐƠN HÀNG</th><th style="padding:10px 16px;text-align:right;">DOANH THU</th>
                </tr></thead>
                <tbody>
                    @foreach (var r in _revenueReport)
                    {
                        var periodLabel = _reportPeriod switch {
                            "weekly" => $"Tuần {r.PeriodStart:dd/MM}",
                            "monthly" => r.PeriodStart.ToString("MM/yyyy"),
                            _ => r.PeriodStart.ToString("dd/MM/yyyy")
                        };
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:10px 16px;color:var(--admin-text-primary);font-weight:500;">@periodLabel</td>
                            <td style="padding:10px 16px;text-align:right;color:var(--admin-text-secondary);">@r.OrderCount</td>
                            <td style="padding:10px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(r.Revenue)</td>
                        </tr>
                    }
                    <tr style="border-top:2px solid var(--admin-orange-primary);font-weight:700;">
                        <td style="padding:10px 16px;color:var(--admin-text-primary);">Tổng cộng</td>
                        <td style="padding:10px 16px;text-align:right;color:var(--admin-text-primary);">@_revenueReport.Sum(r => r.OrderCount)</td>
                        <td style="padding:10px 16px;text-align:right;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(_revenueReport.Sum(r => r.Revenue))</td>
                    </tr>
                </tbody>
            </table>
        }
        else
        {
            <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);font-size:14px;">Không có dữ liệu cho khoảng thời gian đã chọn.</div>
        }
    </div>
</div>

@* ─── Top Products ─── *@
@if (_topProducts.Any())
{
    <div class="admin-panel" style="margin-bottom:16px;">
        <div class="admin-panel__header"><h3 style="font-size:14px;font-weight:700;margin:0;">Top sản phẩm bán chạy</h3></div>
        <div class="admin-panel__body" style="padding:0;">
            <table class="admin-table" style="width:100%;"><thead><tr>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">#</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tên SP</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Đã bán</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Doanh thu</th>
            </tr></thead><tbody>
                @{ var tpRank = 1; }
                @foreach (var tp in _topProducts)
                {
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-weight:700;color:var(--admin-orange-primary);">@(tpRank++)</td>
                        <td style="padding:12px 16px;font-weight:600;">@(tp.ProductName ?? "—")</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:#3B82F6;">@tp.TotalQuantity</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(tp.TotalRevenue)</td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
}

@* ─── Recent Orders ─── *@
@if (filteredOrders.Any())
{
    <div class="admin-panel">
        <div class="admin-panel__header">
            <h3 style="font-size:14px;font-weight:700;margin:0;">Đơn hàng gần nhất</h3>
            <span style="font-size:12px;color:var(--admin-text-tertiary);">@filteredOrders.Count đơn</span>
        </div>
        <div class="admin-panel__body" style="padding:0;">
            <table class="admin-table" style="width:100%;"><thead><tr>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mã đơn</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Giá trị</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Trạng thái</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngày tạo</th>
            </tr></thead><tbody>
                @foreach (var o in filteredOrders.Take(20))
                {
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-family:monospace;font-size:12px;font-weight:600;">@o.Id.ToString()[..8]</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(o.TotalAmount)</td>
                        <td style="padding:12px 16px;"><span class="admin-status-badge admin-status-badge--@ShopHelpers.OrderStatusBadge(o.Status)" style="font-size:10px;"><span class="admin-status-badge__dot"></span>@ShopHelpers.OrderStatusLabel(o.Status)</span></td>
                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@o.CreatedAt.ToString("dd/MM/yyyy HH:mm")</td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
}
else
{
    <div style="text-align:center;padding:40px 20px;">
        <div style="width:64px;height:64px;border-radius:20px;background:rgba(34,197,94,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
            <i data-lucide="bar-chart-2" style="width:28px;height:28px;color:#22C55E;"></i>
        </div>
        <h3 style="font-size:16px;font-weight:700;margin:0 0 6px;color:var(--pos-text-primary, #FFF);">Chưa có đơn hàng trong khoảng thời gian này</h3>
        <p style="font-size:13px;color:var(--admin-text-tertiary);margin:0;">Thử mở rộng khoảng thời gian hoặc tạo đơn hàng mới qua POS</p>
    </div>
}

@code {
    [Parameter] public Guid ShopId { get; set; }

    private List<PosDataService.OrderInfo> _allOrders = new();
    private List<PosDataService.AdminProductInfo> _reportProducts = new();
    private List<PosDataService.TopProductInfo> _topProducts = new();
    private List<PosDataService.RevenueReportItem> _revenueReport = new();
    private string _reportPeriod = "daily";
    private bool _loadingRevenue;
    private DateTime _startDate = DateTime.UtcNow.AddDays(-30).Date;
    private DateTime _endDate = DateTime.UtcNow.Date;
    private int _activeDateRange = 30;

    protected override async Task OnInitializedAsync()
    {
        var shopGuid = ShopId != Guid.Empty ? ShopId : (Guid?)null;
        // EN: Fetch all orders (not just today) for complete reporting
        // VI: Lấy toàn bộ đơn hàng (không chỉ hôm nay) để báo cáo đầy đủ
        _allOrders = await DataService.GetOrdersAsync(shopGuid, "all");
        _reportProducts = await DataService.GetAllProductsAsync(shopGuid);
        _topProducts = await DataService.GetTopProductsAsync(shopGuid);
        // EN: Auto-load revenue report with default period
        // VI: Tự động tải báo cáo doanh thu với kỳ mặc định
        await LoadRevenueReport(_reportPeriod);
    }

    private List<PosDataService.OrderInfo> GetFilteredOrders()
    {
        var start = _startDate.Date;
        var end = _endDate.Date.AddDays(1); // inclusive end date
        return _allOrders.Where(o => o.CreatedAt >= start && o.CreatedAt < end).ToList();
    }

    private void SetDateRange(int days)
    {
        _activeDateRange = days;
        if (days == 0)
        {
            // EN: "All" — show all orders
            // VI: "Tất cả" — hiển thị tất cả đơn hàng
            _startDate = _allOrders.Any() ? _allOrders.Min(o => o.CreatedAt).Date : DateTime.UtcNow.AddYears(-1).Date;
            _endDate = DateTime.UtcNow.Date;
        }
        else
        {
            _startDate = DateTime.UtcNow.AddDays(-days).Date;
            _endDate = DateTime.UtcNow.Date;
        }
        StateHasChanged();
    }

    private void OnStartDateChanged(ChangeEventArgs e)
    {
        if (DateTime.TryParse(e.Value?.ToString(), out var d))
        {
            _startDate = d;
            _activeDateRange = -1; // deselect preset
            StateHasChanged();
        }
    }

    private void OnEndDateChanged(ChangeEventArgs e)
    {
        if (DateTime.TryParse(e.Value?.ToString(), out var d))
        {
            _endDate = d;
            _activeDateRange = -1;
            StateHasChanged();
        }
    }

    private async Task LoadRevenueReport(string period)
    {
        _reportPeriod = period;
        _loadingRevenue = true;
        StateHasChanged();
        try
        {
            _revenueReport = await DataService.GetRevenueReportAsync(period, ShopId != Guid.Empty ? ShopId : null);
        }
        catch { _revenueReport = new(); }
        _loadingRevenue = false;
    }

    private async Task ExportCsv()
    {
        var orders = GetFilteredOrders();
        if (!orders.Any()) return;

        var csv = new System.Text.StringBuilder();
        csv.AppendLine("Mã đơn,Số tiền,Trạng thái,Thanh toán,Ngày tạo");
        foreach (var o in orders)
        {
            csv.AppendLine($"{o.Id},{o.TotalAmount},{o.Status ?? ""},{o.PaymentMethod ?? ""},{o.CreatedAt:yyyy-MM-dd HH:mm:ss}");
        }

        // EN: Summary row
        // VI: Dòng tổng kết
        csv.AppendLine();
        csv.AppendLine($"Tổng doanh thu,{orders.Sum(o => o.TotalAmount)}");
        csv.AppendLine($"Tổng đơn hàng,{orders.Count}");
        csv.AppendLine($"TB/đơn,{(orders.Any() ? orders.Average(o => o.TotalAmount) : 0):F0}");
        csv.AppendLine($"Khoảng thời gian,{_startDate:dd/MM/yyyy} - {_endDate:dd/MM/yyyy}");

        var fileName = $"bao-cao-{ShopId.ToString()[..8]}_{_startDate:yyyyMMdd}_{_endDate:yyyyMMdd}.csv";
        var bytes = System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(csv.ToString())).ToArray();
        var base64 = Convert.ToBase64String(bytes);
        await JS.InvokeVoidAsync("eval", $"((d,n)=>{{const a=document.createElement('a');a.href='data:text/csv;base64,'+d;a.download=n;a.click()}})('{base64}','{fileName}')");
    }
}
