@page "/admin/shop/{ShopId}/overview"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@using WebClientTpos.Client.Services

@*
    EN: Shop overview — KPIs and info when inside a shop context.
        Triggers AdminLayout._isShopContext → per-vertical sidebar.
    VI: Tổng quan cửa hàng — KPI khi đang trong context cửa hàng.
        Kích hoạt AdminLayout._isShopContext → sidebar theo ngành hàng.
*@

<PageTitle>@(_shop?.Name ?? "Cửa hàng") — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Tổng quan</h1>
        <p class="admin-topbar__subtitle">@(_shop?.Name ?? "Đang tải...") • @(_shop?.Category ?? "—")</p>
    </div>
    <div class="admin-topbar__right">
        @if (_shop != null)
        {
            <div class="admin-status-badge admin-status-badge--@GetStatusBadgeClass(_shop.Status)">
                <span class="admin-status-badge__dot"></span>
                @GetStatusLabel(_shop.Status)
            </div>
        }
        <a href="/pos/@ShopId/@(_posVertical)" class="admin-btn-primary" style="text-decoration:none;">
            <i data-lucide="monitor"></i>
            <span>Mở POS</span>
        </a>
    </div>
</div>

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

    @if (IsLoading)
    {
        <div style="text-align:center;padding:48px 20px;">
            <div class="spinner-small" style="width:32px;height:32px;margin:0 auto 16px;"></div>
            <p style="color:var(--admin-text-tertiary);font-size:14px;">Đang tải thông tin cửa hàng...</p>
        </div>
    }
    else if (_shop == null)
    {
        <div style="text-align:center;padding:48px 20px;">
            <i data-lucide="alert-circle" style="width:48px;height:48px;color:#EF4444;margin-bottom:16px;"></i>
            <h3 style="font-size:18px;font-weight:700;color:var(--pos-text-primary, #FFFFFF);margin:0 0 8px;">Không tìm thấy cửa hàng</h3>
            <p style="font-size:14px;color:var(--pos-text-tertiary, #ADADB0);margin:0 0 20px;">Cửa hàng không tồn tại hoặc đã bị xóa.</p>
            <a href="/admin/stores" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;">
                <i data-lucide="arrow-left" style="width:16px;height:16px;"></i>
                Quay lại danh sách
            </a>
        </div>
    }
    else
    {
        @* ── Store Info Card ── *@
        <div class="admin-panel">
            <div class="admin-panel__body" style="display:flex;gap:20px;align-items:center;">
                <div class="admin-store-card__avatar" style="width:64px;height:64px;background-color:rgba(255,92,0,0.125);border-radius:16px;">
                    <i data-lucide="@ShopVerticalHelper.GetIcon(_shop.Category)" style="color:var(--admin-orange-primary);width:28px;height:28px;"></i>
                </div>
                <div style="flex:1;">
                    <div style="font-size:18px;font-weight:700;">@_shop.Name</div>
                    <div style="font-size:13px;color:var(--admin-text-tertiary);">@_shop.Slug • @ShopSidebarConfig.GetVerticalLabel(_shop.Category)</div>
                    @if (!string.IsNullOrEmpty(_shop.Description))
                    {
                        <div style="font-size:13px;color:var(--admin-text-tertiary);margin-top:4px;">@_shop.Description</div>
                    }
                </div>
                <div style="display:flex;flex-direction:column;gap:4px;align-items:flex-end;">
                    @if (!string.IsNullOrEmpty(_shop.Phone))
                    {
                        <div style="font-size:13px;color:var(--admin-text-tertiary);display:flex;align-items:center;gap:6px;">
                            <i data-lucide="phone" style="width:14px;height:14px;"></i> @_shop.Phone
                        </div>
                    }
                    @if (!string.IsNullOrEmpty(_shop.Email))
                    {
                        <div style="font-size:13px;color:var(--admin-text-tertiary);display:flex;align-items:center;gap:6px;">
                            <i data-lucide="mail" style="width:14px;height:14px;"></i> @_shop.Email
                        </div>
                    }
                </div>
            </div>
        </div>

        @* ── Date Range Selector ── *@
        <div style="display:flex;align-items:center;gap:8px;">
            <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
                @foreach (var (label, days) in new[] { ("Hôm nay", 0), ("7 ngày", 7), ("30 ngày", 30), ("Tất cả", -1) })
                {
                    <button @onclick="@(() => SetPeriod(days))"
                        style="padding:6px 14px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;border:none;
                            background:@(_activePeriod == days ? "var(--admin-orange-primary)" : "transparent");
                            color:@(_activePeriod == days ? "#FFF" : "var(--admin-text-tertiary)");">
                        @label
                    </button>
                }
            </div>
            <span style="font-size:12px;color:var(--admin-text-tertiary);">@GetPeriodLabel()</span>
        </div>

        @* ── KPI ROW ── *@
        <div class="admin-kpi-row">
            <div class="admin-kpi-card">
                <div class="admin-kpi-card__header">
                    <div class="admin-kpi-card__icon" style="background-color:rgba(34,197,94,0.125);">
                        <i data-lucide="trending-up" style="color:#22C55E;"></i>
                    </div>
                </div>
                <div class="admin-kpi-card__value">@FormatVND(GetFilteredOrders().Sum(o => o.TotalAmount))</div>
                <div class="admin-kpi-card__label">Doanh thu</div>
            </div>
            <div class="admin-kpi-card">
                <div class="admin-kpi-card__header">
                    <div class="admin-kpi-card__icon" style="background-color:rgba(59,130,246,0.125);">
                        <i data-lucide="shopping-bag" style="color:#3B82F6;"></i>
                    </div>
                </div>
                <div class="admin-kpi-card__value">@GetFilteredOrders().Count</div>
                <div class="admin-kpi-card__label">Đơn hàng</div>
            </div>
            <div class="admin-kpi-card">
                <div class="admin-kpi-card__header">
                    <div class="admin-kpi-card__icon" style="background-color:rgba(139,92,246,0.125);">
                        <i data-lucide="banknote" style="color:#8B5CF6;"></i>
                    </div>
                </div>
                <div class="admin-kpi-card__value">@FormatVND(GetFilteredOrders().Any() ? GetFilteredOrders().Average(o => o.TotalAmount) : 0)</div>
                <div class="admin-kpi-card__label">Giá trị TB / đơn</div>
            </div>
            <div class="admin-kpi-card">
                <div class="admin-kpi-card__header">
                    <div class="admin-kpi-card__icon" style="background-color:rgba(236,72,153,0.125);">
                        <i data-lucide="package" style="color:#EC4899;"></i>
                    </div>
                </div>
                <div class="admin-kpi-card__value">@_products.Count</div>
                <div class="admin-kpi-card__label">Sản phẩm</div>
            </div>
        </div>

        @* ── BOTTOM: Chart + Right Column ── *@
        <div style="display:flex;gap:24px;flex:1;min-height:0;">
            @* LEFT: Revenue Chart *@
            <div class="admin-panel" style="flex:1;">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="bar-chart-2" style="color:var(--admin-orange-primary);"></i>
                        Biểu đồ doanh thu
                    </h3>
                    <div style="display:flex;gap:8px;">
                        <button class="admin-tab @(_revenuePeriod == "daily" ? "admin-tab--active" : "")" style="padding:6px 12px;font-size:12px;" @onclick="@(() => SwitchRevenuePeriod("daily"))">Ngày</button>
                        <button class="admin-tab @(_revenuePeriod == "weekly" ? "admin-tab--active" : "")" style="padding:6px 12px;font-size:12px;" @onclick="@(() => SwitchRevenuePeriod("weekly"))">Tuần</button>
                        <button class="admin-tab @(_revenuePeriod == "monthly" ? "admin-tab--active" : "")" style="padding:6px 12px;font-size:12px;" @onclick="@(() => SwitchRevenuePeriod("monthly"))">Tháng</button>
                    </div>
                </div>
                <div class="admin-panel__body" style="min-height:200px;">
                    @if (_dailyRevenue.Any())
                    {
                        var recent = _revenuePeriod switch {
                            "monthly" => _dailyRevenue.TakeLast(12).ToList(),
                            "weekly" => _dailyRevenue.TakeLast(8).ToList(),
                            _ => _dailyRevenue.TakeLast(7).ToList()
                        };
                        var maxVal = recent.Max(r => r.Revenue);
                        <div style="display:flex;align-items:flex-end;gap:8px;height:200px;padding:0 8px;">
                            @foreach (var r in recent)
                            {
                                var pct = maxVal > 0 ? (int)(r.Revenue / maxVal * 100) : 0;
                                var barLabel = _revenuePeriod switch {
                                    "monthly" => r.PeriodStart.ToString("MM/yy"),
                                    "weekly" => $"T{r.PeriodStart:dd/MM}",
                                    _ => r.PeriodStart.ToString("dd/MM")
                                };
                                <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;min-width:0;">
                                    <span style="font-size:10px;font-weight:600;color:var(--admin-orange-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;">@FormatVND(r.Revenue)</span>
                                    <div style="width:100%;height:@(Math.Max(pct, 4))%;min-height:4px;background:var(--admin-orange-primary);border-radius:6px 6px 0 0;transition:height 0.3s;"></div>
                                    <span style="font-size:10px;color:var(--admin-text-tertiary);">@barLabel</span>
                                </div>
                            }
                        </div>
                    }
                    else
                    {
                        <div style="display:flex;align-items:center;justify-content:center;height:200px;text-align:center;color:var(--admin-text-tertiary);">
                            <div>
                                <i data-lucide="bar-chart-2" style="width:40px;height:40px;margin-bottom:12px;opacity:0.5;"></i>
                                <p style="font-size:14px;margin:0;">Chưa có dữ liệu doanh thu</p>
                                <p style="font-size:12px;margin:4px 0 0;">Dữ liệu sẽ hiển thị khi có đơn hàng</p>
                            </div>
                        </div>
                    }
                </div>
            </div>

            @* RIGHT COLUMN *@
            <div style="width:380px;display:flex;flex-direction:column;gap:20px;">
                <div class="admin-panel">
                    <div class="admin-panel__header">
                        <h3 class="admin-panel__title">
                            <i data-lucide="shopping-bag" style="color:#3B82F6;"></i>
                            Đơn gần nhất
                        </h3>
                    </div>
                <div class="admin-panel__body" style="padding:0;">
                    @if (GetFilteredOrders().Any())
                    {
                        <div style="display:flex;flex-direction:column;">
                            @foreach (var o in GetFilteredOrders().Take(5))
                            {
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid var(--admin-border-subtle);">
                                    <div style="display:flex;flex-direction:column;gap:2px;">
                                        <span style="font-size:12px;font-family:monospace;color:var(--admin-text-tertiary);">@o.Id.ToString()[..8]</span>
                                        <span style="font-size:11px;color:var(--admin-text-tertiary);">@o.CreatedAt.ToString("dd/MM HH:mm")</span>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:8px;">
                                        <span class="admin-status-badge admin-status-badge--@ShopHelpers.OrderStatusBadge(o.Status)" style="font-size:10px;padding:2px 8px;"><span class="admin-status-badge__dot" style="width:4px;height:4px;"></span>@ShopHelpers.OrderStatusLabel(o.Status)</span>
                                        <span style="font-weight:600;font-size:13px;">@FormatVND(o.TotalAmount)</span>
                                    </div>
                                </div>
                            }
                        </div>
                    }
                    else
                    {
                        <div style="text-align:center;padding:20px;color:var(--admin-text-tertiary);font-size:14px;">
                            <i data-lucide="inbox" style="width:32px;height:32px;margin-bottom:8px;opacity:0.5;"></i>
                            <p style="margin:0;">Chưa có đơn hàng nào</p>
                        </div>
                    }
                </div>
                </div>

                <div class="admin-panel" style="flex:1;">
                    <div class="admin-panel__header">
                        <h3 class="admin-panel__title">
                            <i data-lucide="info" style="color:#22C55E;"></i>
                            Thông tin
                        </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;">
                            <span style="color:var(--admin-text-tertiary);font-size:14px;">Trạng thái</span>
                            <span style="font-size:13px;font-weight:600;">@GetStatusLabel(_shop.Status)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;align-items:center;">
                            <span style="color:var(--admin-text-tertiary);font-size:14px;">Ngành hàng</span>
                            <span style="font-size:13px;font-weight:600;">@ShopSidebarConfig.GetVerticalLabel(_shop.Category)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;align-items:center;">
                            <span style="color:var(--admin-text-tertiary);font-size:14px;">Slug</span>
                            <span style="font-size:13px;font-weight:600;">@(_shop.Slug)</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }

</div>

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

    private PosDataService.ShopInfo? _shop;
    private string _posVertical = "cafe";
    private List<PosDataService.OrderInfo> _allOrders = new();
    private List<PosDataService.AdminProductInfo> _products = new();
    private List<PosDataService.RevenueReportItem> _dailyRevenue = new();
    private string _revenuePeriod = "daily";
    private int _activePeriod = 30; // default 30 days

    [CascadingParameter] public AdminLayout? Layout { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        IsLoading = true;
        try
        {
            if (Guid.TryParse(ShopId, out var id))
            {
                _shop = await DataService.GetShopByIdAsync(id);
                if (_shop != null)
                {
                    _posVertical = MapCategoryToVertical(_shop.Category);
                    Layout?.SetShopContext(ShopId, _shop.Name ?? "Cửa hàng", _shop.Category);
                }
                // EN: Load all orders + products + revenue in parallel
                // VI: Tải tất cả đơn hàng + sản phẩm + doanh thu song song
                var ordersTask = DataService.GetOrdersAsync(id, "all");
                var productsTask = DataService.GetAllProductsAsync(id);
                var revenueTask = DataService.GetRevenueReportAsync("daily", id);
                _allOrders = await ordersTask;
                _products = await productsTask;
                try { _dailyRevenue = await revenueTask; } catch { _dailyRevenue = new(); }
            }
        }
        catch (Exception ex)
        {
            _shop = null;
            Console.Error.WriteLine($"[ShopOverview] Error loading shop {ShopId}: {ex}");
        }
        finally { IsLoading = false; }
    }

    private List<PosDataService.OrderInfo> GetFilteredOrders()
    {
        if (_activePeriod == -1) return _allOrders; // all
        if (_activePeriod == 0) return _allOrders.Where(o => o.CreatedAt.Date == DateTime.UtcNow.Date).ToList(); // today
        return _allOrders.Where(o => o.CreatedAt >= DateTime.UtcNow.AddDays(-_activePeriod)).ToList();
    }

    private void SetPeriod(int days)
    {
        _activePeriod = days;
        StateHasChanged();
    }

    private string GetPeriodLabel() => _activePeriod switch
    {
        0 => DateTime.UtcNow.ToString("dd/MM/yyyy"),
        -1 => "Toàn bộ thời gian",
        _ => $"{DateTime.UtcNow.AddDays(-_activePeriod):dd/MM} — {DateTime.UtcNow:dd/MM/yyyy}"
    };

    private async Task SwitchRevenuePeriod(string period)
    {
        _revenuePeriod = period;
        if (Guid.TryParse(ShopId, out var id))
        {
            try { _dailyRevenue = await DataService.GetRevenueReportAsync(period, id); } catch { }
        }
        StateHasChanged();
    }

    private static string FormatVND(decimal val) => val.ToString("N0") + " ₫";
    private static string GetStatusBadgeClass(string? status) => ShopVerticalHelper.GetStatusBadgeClass(status);
    private static string GetStatusLabel(string? status) => ShopVerticalHelper.GetStatusLabel(status);

    private static string MapCategoryToVertical(string? category) => (category?.ToLowerInvariant()) switch
    {
        "cafe" or "coffee" => "cafe",
        "restaurant" or "nhahang" => "restaurant",
        "karaoke" => "karaoke",
        "spa" or "beauty" => "spa",
        "retail" or "banle" => "retail",
        _ => "cafe"
    };
}
