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

<div style="padding:8px 14px;border-radius:8px;background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.15);margin-bottom:12px;display:flex;align-items:center;gap:8px;font-size:12px;color:var(--admin-text-secondary);">
    <i data-lucide="info" style="width:14px;height:14px;color:#3B82F6;flex-shrink:0;"></i>
    Đơn hàng theo cửa hàng · Ví tiền chung cho tài khoản
</div>
@{
    var finOrders = _financePeriod switch {
        "7d" => _orders.Where(o => o.CreatedAt >= DateTime.UtcNow.AddDays(-7)).ToList(),
        "30d" => _orders.Where(o => o.CreatedAt >= DateTime.UtcNow.AddDays(-30)).ToList(),
        _ => _orders };
}
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <h3 style="margin:0;font-size:16px;font-weight:700;">Tài chính</h3>
    <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
        @foreach (var (label, val) in new[] { ("7 ngày", "7d"), ("30 ngày", "30d"), ("Tất cả", "all") })
        {
            <button @onclick="@(() => { _financePeriod = val; StateHasChanged(); })"
                style="padding:6px 14px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;border:none;
                    background:@(_financePeriod == val ? "var(--admin-orange-primary)" : "transparent");
                    color:@(_financePeriod == val ? "#FFF" : "var(--admin-text-tertiary)");">
                @label
            </button>
        }
    </div>
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
    <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(finOrders.Sum(o => o.TotalAmount))</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="receipt" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@finOrders.Count</span><span class="admin-stat-card__label">Đơn hàng</span></div></div>
    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(255,92,0,0.1);"><i data-lucide="calculator" style="color:#FF5C00;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@ShopHelpers.FormatVND(finOrders.Any() ? finOrders.Average(o => o.TotalAmount) : 0)</span><span class="admin-stat-card__label">TB/đơn</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="wallet" style="color:#8B5CF6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@ShopHelpers.FormatVND(_wallets.Sum(w => w.Balance))</span><span class="admin-stat-card__label">Số dư ví</span></div></div>
</div>
@if (_walletTxns.Any())
{
    <div class="admin-panel" style="margin-top:16px;">
        <div class="admin-panel__header"><h3 class="admin-panel__title">Giao dịch ví gần đâ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);">Mô tả</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Số tiền</th>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngày</th>
            </tr></thead><tbody>
                @foreach (var t in _walletTxns.Take(15))
                {
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-weight:600;font-size:13px;">@(t.Description ?? t.ItemName ?? "—")</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:@(t.Amount >= 0 ? "#22C55E" : "#EF4444");">@(t.Amount >= 0 ? "+" : "")@ShopHelpers.FormatVND(t.Amount)</td>
                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@t.CreatedAt.ToString("dd/MM HH:mm")</td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
}
@if (_orders.Any())
{
    <div class="admin-panel" style="margin-top:16px;">
        <div class="admin-panel__header"><h3 class="admin-panel__title">Đơn hàng gần đâ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);">ID</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Số tiền</th>
                <th style="padding:12px 16px;text-align:center;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</th>
                <th style="padding:12px 16px;width:32px;"></th>
            </tr></thead><tbody>
                @foreach (var o in _orders.Take(20))
                {
                    var isOrderExpanded = _selectedOrderId == o.Id;
                    <tr style="border-top:1px solid var(--admin-border-subtle);cursor:pointer;@(isOrderExpanded ? "background:rgba(255,92,0,0.05);" : "")" @onclick="@(() => ViewOrderDetail(o.Id))">
                        <td style="padding:12px 16px;font-size:12px;font-family:monospace;color:var(--admin-text-tertiary);">@o.Id.ToString()[..8]</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;">@ShopHelpers.FormatVND(o.TotalAmount)</td>
                        <td style="padding:12px 16px;text-align:center;"><span class="admin-status-badge admin-status-badge--@ShopHelpers.OrderStatusBadge(o.Status)" style="font-size:11px;padding:2px 10px;">@ShopHelpers.OrderStatusLabel(o.Status)</span></td>
                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@o.CreatedAt.ToString("dd/MM HH:mm")</td>
                        <td style="padding:12px 16px;text-align:center;"><i data-lucide="@(isOrderExpanded ? "chevron-up" : "chevron-down")" style="width:14px;height:14px;color:var(--admin-text-tertiary);"></i></td>
                    </tr>
                    @if (isOrderExpanded && _orderDetail != null)
                    {
                        <tr><td colspan="5" style="padding:0;">
                            <div style="padding:16px 20px;background:rgba(255,92,0,0.03);border-top:2px solid var(--admin-orange-primary);">
                                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:12px;">
                                    <div><label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">💳 Thanh toán</label><div style="font-size:13px;">@(_orderDetail.Order?.PaymentMethod ?? "—")</div></div>
                                    <div><label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">📝 Ghi chú</label><div style="font-size:13px;">@(_orderDetail.Order?.Notes ?? "—")</div></div>
                                    <div><label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">🕐 Thời gian</label><div style="font-size:13px;">@(_orderDetail.Order?.CreatedAt.ToString("dd/MM/yyyy HH:mm") ?? "—")</div></div>
                                </div>
                                @if (_orderDetail.Items?.Any() == true)
                                {
                                    <table style="width:100%;border-collapse:collapse;font-size:13px;"><thead><tr style="color:var(--admin-text-tertiary);font-size:11px;">
                                        <th style="text-align:left;padding:4px 8px;">Sản phẩm</th><th style="text-align:center;padding:4px 8px;">SL</th><th style="text-align:right;padding:4px 8px;">Đơn giá</th><th style="text-align:right;padding:4px 8px;">Thành tiền</th>
                                    </tr></thead><tbody>
                                        @foreach (var item in _orderDetail.Items)
                                        {
                                            <tr style="border-top:1px solid var(--admin-border-subtle);">
                                                <td style="padding:6px 8px;font-weight:500;">@(item.ProductName ?? "—")</td>
                                                <td style="padding:6px 8px;text-align:center;">@item.Quantity</td>
                                                <td style="padding:6px 8px;text-align:right;">@ShopHelpers.FormatVND(item.UnitPrice)</td>
                                                <td style="padding:6px 8px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(item.Subtotal)</td>
                                            </tr>
                                        }
                                    </tbody></table>
                                }
                                <div style="display:flex;gap:8px;margin-top:12px;">
                                    <button @onclick="@(() => CancelOrderItem(o.Id))" style="padding:6px 14px;border-radius:8px;border:1px solid rgba(239,68,68,0.3);background:rgba(239,68,68,0.1);color:#EF4444;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                        <i data-lucide="x-circle" style="width:12px;height:12px;"></i> Hủy đơn
                                    </button>
                                </div>
                            </div>
                        </td></tr>
                    }
                }
            </tbody></table>
        </div>
    </div>
}
else
{
    @RenderEmpty("bar-chart-3", "#22C55E", "Chưa có dữ liệu tài chính", "Dữ liệu sẽ tự động cập nhật khi có đơn hàng", "monitor", "Mở POS bán hàng", $"/pos/{ShopId}/{PosVertical}")
}

@code {
    [Parameter] public Guid ShopId { get; set; }
    [Parameter] public string PosVertical { get; set; } = "cafe";

    // Finance data
    private List<PosDataService.OrderInfo> _orders = new();
    private List<PosDataService.WalletInfo> _wallets = new();
    private List<PosDataService.WalletTxnInfo> _walletTxns = new();
    // Finance date range filter state
    private string _financePeriod = "all"; // 7d, 30d, all
    // Order detail state
    private Guid? _selectedOrderId;
    private PosDataService.OrderDetailResponse? _orderDetail;

    protected override async Task OnInitializedAsync()
    {
        _orders = await DataService.GetOrdersAsync(ShopId == Guid.Empty ? null : ShopId, "all");
        _wallets = await DataService.GetWalletsAsync();
        _walletTxns = await DataService.GetWalletTransactionsAsync();
    }

    // ═══ ORDER DETAIL ═══
    private async Task ViewOrderDetail(Guid orderId)
    {
        if (_selectedOrderId == orderId) { _selectedOrderId = null; _orderDetail = null; return; }
        _selectedOrderId = orderId;
        try { _orderDetail = await DataService.GetOrderDetailAsync(orderId, ShopId == Guid.Empty ? null : ShopId); }
        catch { _orderDetail = null; }
    }

    private async Task CancelOrderItem(Guid orderId)
    {
        var ok = await DataService.CancelOrderAsync(orderId);
        if (ok)
        {
            _selectedOrderId = null;
            _orderDetail = null;
            _orders = await DataService.GetOrdersAsync(ShopId == Guid.Empty ? null : ShopId);
        }
    }

    private RenderFragment RenderEmpty(string icon, string color, string title, string desc, string? ctaIcon = null, string? ctaLabel = null, string? ctaHref = null) => __builder =>
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({ShopHelpers.HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">@title</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">@desc</p>
            @if (ctaIcon != null && ctaLabel != null)
            {
                <a href="@(ctaHref ?? $"/admin/shop/{ShopId}/menu")" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                    <i data-lucide="@ctaIcon" style="width:16px;height:16px;"></i>
                    @ctaLabel
                </a>
            }
        </div>
    };
}
