@page "/admin"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject Microsoft.Extensions.Localization.IStringLocalizer<Dashboard> L
@using WebClientTpos.Client.Services

@*
    EN: Admin Dashboard — overview with real data from shops list.
    VI: Dashboard Admin — tổng quan với dữ liệu thực từ danh sách shops.
*@

<PageTitle>Dashboard — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">@L["Dashboard_Title"]</h1>
        <p class="admin-topbar__subtitle">@L["Dashboard_Subtitle"] • @GetTodayFormatted()</p>
    </div>
    <div class="admin-topbar__right">
        <div class="admin-search">
            <i data-lucide="search"></i>
            <input type="text" placeholder="@L["Dashboard_Search"]" @bind="SearchQuery" @bind:event="oninput" />
        </div>
        <button class="admin-icon-btn" title="Thông báo">
            <i data-lucide="bell"></i>
        </button>
        <button class="admin-btn-primary" @onclick="@(() => NavigateTo("stores/create"))">
            <i data-lucide="plus"></i>
            <span>@L["Dashboard_CreateStore"]</span>
        </button>
    </div>
</div>

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

    @* ── KPI ROW (data-driven) ── *@
    <div class="admin-kpi-row">
        @* KPI 1: Cửa hàng *@
        <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="store" style="color:#8B5CF6;"></i>
                </div>
            </div>
            <div class="admin-kpi-card__value">@_shops.Count</div>
            <div class="admin-kpi-card__label">@L["Dashboard_KPI_Stores"]</div>
        </div>

        @* KPI 2: Đang hoạt động *@
        <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="check-circle" style="color:#22C55E;"></i>
                </div>
            </div>
            <div class="admin-kpi-card__value">@_shops.Count(s => ShopVerticalHelper.IsActive(s.Status))</div>
            <div class="admin-kpi-card__label">@L["Dashboard_KPI_Active"]</div>
        </div>

        @* KPI 3: Đang thiết lập *@
        <div class="admin-kpi-card">
            <div class="admin-kpi-card__header">
                <div class="admin-kpi-card__icon" style="background-color:rgba(245,158,11,0.125);">
                    <i data-lucide="settings" style="color:#F59E0B;"></i>
                </div>
            </div>
            <div class="admin-kpi-card__value">@_shops.Count(s => !ShopVerticalHelper.IsActive(s.Status))</div>
            <div class="admin-kpi-card__label">@L["Dashboard_KPI_Setup"]</div>
        </div>

        @* KPI 4: Ngành hàng *@
        <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="layers" style="color:#EC4899;"></i>
                </div>
            </div>
            <div class="admin-kpi-card__value">@_shops.Select(s => s.Category).Distinct().Count()</div>
            <div class="admin-kpi-card__label">@L["Dashboard_KPI_Verticals"]</div>
        </div>
    </div>

    @* ── BOTTOM ROW ── *@
    <div style="display:flex;gap:24px;flex:1;min-height:0;">

        @* ── LEFT: Store Overview ── *@
        <div class="admin-panel" style="flex:1;">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="store" style="color:var(--admin-orange-primary);"></i>
                    Cửa hàng của bạn
                </h3>
                @if (_shops.Count > 0)
                {
                    <a href="/admin/stores" class="admin-panel__action">@L["Dashboard_ManageAll"] →</a>
                }
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:12px;">
                @if (_shops.Count == 0)
                {
                    <div style="text-align:center;padding:40px 20px;">
                        <i data-lucide="store" style="width:48px;height:48px;color:var(--admin-orange-primary);margin-bottom:16px;"></i>
                        <h3 style="font-size:18px;font-weight:700;color:var(--pos-text-primary, #FFFFFF);margin:0 0 8px;">@L["Dashboard_WelcomeTitle"]</h3>
                        <p style="font-size:14px;color:var(--pos-text-tertiary, #ADADB0);margin:0 0 20px;">@L["Dashboard_WelcomeSubtitle"]</p>
                        <a href="/admin/stores/create" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;">
                            <i data-lucide="plus" style="width:16px;height:16px;"></i>
                            @L["Dashboard_CreateStoreNow"]
                        </a>
                    </div>
                }
                else
                {
                    @foreach (var shop in FilteredShops)
                    {
                        var stats = _shopStats.FirstOrDefault(s => s.ShopId == shop.Id);
                        <a href="/admin/shop/@shop.Id/overview" class="admin-store-card" style="text-decoration:none;color:inherit;cursor:pointer;">
                            <div class="admin-store-card__top">
                                <div class="admin-store-card__info">
                                    <div class="admin-store-card__avatar" style="background-color:rgba(255,92,0,0.125);">
                                        <i data-lucide="@ShopVerticalHelper.GetIcon(shop.Category)" style="color:var(--admin-orange-primary);"></i>
                                    </div>
                                    <div>
                                        <div class="admin-store-card__name">@shop.Name</div>
                                        <div class="admin-store-card__type">@ShopSidebarConfig.GetVerticalLabel(shop.Category) • @(shop.Slug)</div>
                                    </div>
                                </div>
                                <div style="display:flex;align-items:center;gap:8px;">
                                    @if (ShopVerticalHelper.IsSetup(shop.Status))
                                    {
                                        <button class="admin-btn-primary" style="font-size:12px;padding:6px 12px;"
                                                @onclick:preventDefault @onclick:stopPropagation
                                                @onclick="@(() => PublishShopAsync(shop.Id))">
                                            <i data-lucide="check-circle" style="width:14px;height:14px;"></i>
                                            <span>@L["Dashboard_FinishSetup"]</span>
                                        </button>
                                    }
                                    <div class="admin-status-badge admin-status-badge--@(ShopVerticalHelper.IsActive(shop.Status) ? "online" : "setup")">
                                        <span class="admin-status-badge__dot"></span>
                                        @(ShopVerticalHelper.IsActive(shop.Status) ? L["Dashboard_Status_Open"] : L["Dashboard_Status_Setup"])
                                    </div>
                                </div>
                            </div>
                            @if (stats != null)
                            {
                                <div style="display:flex;gap:16px;padding-top:10px;border-top:1px solid var(--admin-border-subtle);margin-top:10px;">
                                    <div style="display:flex;align-items:center;gap:4px;font-size:12px;color:var(--admin-text-tertiary);">
                                        <i data-lucide="trending-up" style="width:12px;height:12px;color:#22C55E;"></i>
                                        @FormatCurrency(stats.Revenue)
                                    </div>
                                    <div style="display:flex;align-items:center;gap:4px;font-size:12px;color:var(--admin-text-tertiary);">
                                        <i data-lucide="shopping-bag" style="width:12px;height:12px;color:#3B82F6;"></i>
                                        @stats.OrderCount @L["Dashboard_Stats_Orders"]
                                    </div>
                                    <div style="display:flex;align-items:center;gap:4px;font-size:12px;color:var(--admin-text-tertiary);">
                                        <i data-lucide="users" style="width:12px;height:12px;color:#8B5CF6;"></i>
                                        @stats.StaffCount @L["Dashboard_Stats_Staff"]
                                    </div>
                                    <div style="display:flex;align-items:center;gap:4px;font-size:12px;color:var(--admin-text-tertiary);">
                                        <i data-lucide="package" style="width:12px;height:12px;color:#EC4899;"></i>
                                        @stats.ProductCount @L["Dashboard_Stats_Products"]
                                    </div>
                                </div>
                            }
                        </a>
                    }
                }
            </div>
        </div>

        @* ── RIGHT COLUMN ── *@
        <div style="width:380px;display:flex;flex-direction:column;gap:20px;">
            @* Quick Actions Panel *@
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="zap" style="color:var(--admin-orange-primary);"></i>
                        @L["Dashboard_QuickActions"]
                    </h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:8px;">
                    <a href="/admin/stores/create" class="admin-quick-action">
                        <i data-lucide="plus-circle" style="color:#22C55E;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_CreateStore"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/users" class="admin-quick-action">
                        <i data-lucide="users" style="color:#3B82F6;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_ManageStaff"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/roles" class="admin-quick-action">
                        <i data-lucide="shield" style="color:#8B5CF6;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_Permissions"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/system/devices" class="admin-quick-action">
                        <i data-lucide="monitor-smartphone" style="color:#F59E0B;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_Devices"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/system/integrations" class="admin-quick-action">
                        <i data-lucide="plug" style="color:#06B6D4;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_Integrations"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/system/audit" class="admin-quick-action">
                        <i data-lucide="scroll-text" style="color:#EC4899;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_AuditLog"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                    <a href="/admin/settings" class="admin-quick-action">
                        <i data-lucide="settings" style="color:#6B7280;width:18px;height:18px;"></i>
                        <span>@L["Dashboard_QA_SystemSettings"]</span>
                        <i data-lucide="chevron-right" style="margin-left:auto;width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </a>
                </div>
            </div>

            @* Status Panel *@
            <div class="admin-panel" style="flex:1;">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="activity" style="color:#22C55E;"></i>
                        @L["Dashboard_SystemStatus"]
                    </h3>
                    <button class="admin-icon-btn" title="@L["Dashboard_RefreshStatus"]" @onclick="RefreshHealthAsync" disabled="@_healthLoading" style="font-size:12px;">
                        <i data-lucide="refresh-cw" style="width:14px;height:14px;@(_healthLoading ? "animation:spin 1s linear infinite;" : "")"></i>
                    </button>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:12px;">
                    @if (_healthLoading && _serviceHealth.Count == 0)
                    {
                        <div style="text-align:center;padding:16px;color:var(--admin-text-tertiary);font-size:13px;">
                            @L["Dashboard_CheckingServices"]
                        </div>
                    }
                    else
                    {
                        @foreach (var svc in _serviceHealth)
                        {
                            var statusColor = svc.IsOnline ? "#22C55E" : "#EF4444";
                            var statusText = svc.IsOnline ? "Online" : "Offline";
                            <div style="display:flex;justify-content:space-between;align-items:center;">
                                <span style="color:var(--admin-text-tertiary);font-size:14px;display:flex;align-items:center;gap:8px;">
                                    <i data-lucide="@svc.Icon" style="width:14px;height:14px;"></i>
                                    @svc.Name
                                </span>
                                <span style="font-size:13px;color:@statusColor;display:flex;align-items:center;gap:4px;">
                                    @if (svc.IsOnline && svc.LatencyMs.HasValue)
                                    {
                                        <span style="font-size:11px;color:var(--admin-text-tertiary);margin-right:4px;">@(svc.LatencyMs)ms</span>
                                    }
                                    <span style="width:6px;height:6px;border-radius:50%;background:@statusColor;display:inline-block;"></span>
                                    @statusText
                                </span>
                            </div>
                        }
                        @if (_healthCheckedAt.HasValue)
                        {
                            <div style="font-size:11px;color:var(--admin-text-tertiary);text-align:right;margin-top:4px;">
                                @L["Dashboard_LastChecked"] @_healthCheckedAt.Value.ToString("HH:mm:ss")
                            </div>
                        }
                    }
                </div>
            </div>
        </div>
    </div>
</div>

@code {
    private List<PosDataService.ShopInfo> _shops = new();
    private List<PosDataService.ShopStatsInfo> _shopStats = new();
    private List<PosDataService.ServiceHealthInfo> _serviceHealth = new();

    // EN: Filter shops by search query (name, slug, category)
    // VI: Lọc shops theo từ khóa tìm kiếm (tên, slug, ngành hàng)
    private List<PosDataService.ShopInfo> FilteredShops => string.IsNullOrWhiteSpace(SearchQuery)
        ? _shops
        : _shops.Where(s =>
            (s.Name?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) == true) ||
            (s.Slug?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) == true) ||
            (s.Category?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) == true))
        .ToList();
    private bool _healthLoading = false;
    private DateTime? _healthCheckedAt;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        IsLoading = true;
        try
        {
            var shopsTask = DataService.GetShopsAsync();
            var statsTask = DataService.GetShopStatsAsync();
            var healthTask = LoadHealthAsync();
            _shops = await shopsTask;
            try { _shopStats = await statsTask; } catch { _shopStats = new(); }
            await healthTask;
        }
        catch (Exception ex)
        {
            _shops = new();
            Console.Error.WriteLine($"[Dashboard] Error loading data: {ex}");
        }
        finally
        {
            IsLoading = false;
        }
    }

    private async Task PublishShopAsync(Guid shopId)
    {
        var ok = await DataService.PublishShopAsync(shopId);
        if (ok)
        {
            _shops = await DataService.GetShopsAsync();
            StateHasChanged();
        }
    }

    private async Task LoadHealthAsync()
    {
        _healthLoading = true;
        try
        {
            _serviceHealth = await DataService.CheckServicesHealthAsync();
            _healthCheckedAt = DateTime.Now;
        }
        catch
        {
            _serviceHealth = new();
        }
        finally
        {
            _healthLoading = false;
        }
    }

    private async Task RefreshHealthAsync()
    {
        await LoadHealthAsync();
        StateHasChanged();
    }
}
