@page "/superadmin/dashboard"
@page "/superadmin"
@layout SuperAdminLayout
@inherits SuperAdminBase
@inject SuperAdminApiService Api
@inject IamApiService IamApi
@inject Microsoft.Extensions.Localization.IStringLocalizer<Dashboard> L
@using WebClientTpos.Client.Services

@*
    EN: Super Admin Dashboard — platform-wide KPIs and overview.
    VI: Dashboard Super Admin — KPI toàn nền tảng và tổng quan.
*@

<PageTitle>Dashboard — aPOS Super Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="sa-topbar">
    <div class="sa-topbar__left">
        <h1 class="sa-topbar__title">@L["SA_Dashboard_Title"]</h1>
        <p class="sa-topbar__subtitle">@L["SA_Dashboard_Subtitle"] • @GetTodayFormatted()</p>
    </div>
    <div class="sa-topbar__right">
        <button class="sa-btn-outline" @onclick="LoadDataAsync">
            <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i>
            Làm mới
        </button>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="sa-content">

    @* ── KPI ROW ── *@
    <div class="sa-kpi-row">
        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(59,130,246,0.12);">
                    <i data-lucide="building-2" style="color:#3B82F6;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.TotalMerchants ?? 0)</div>
            <div class="sa-kpi-card__label">Tổng doanh nghiệp</div>
        </div>

        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(34,197,94,0.12);">
                    <i data-lucide="check-circle" style="color:#22C55E;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.ActiveMerchants ?? 0)</div>
            <div class="sa-kpi-card__label">Đang hoạt động</div>
        </div>

        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(245,158,11,0.12);">
                    <i data-lucide="clock" style="color:#F59E0B;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.PendingMerchants ?? 0)</div>
            <div class="sa-kpi-card__label">Chờ phê duyệt</div>
        </div>

        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(239,68,68,0.12);">
                    <i data-lucide="alert-triangle" style="color:#EF4444;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.SuspendedMerchants ?? 0)</div>
            <div class="sa-kpi-card__label">Đã tạm ngưng</div>
        </div>

        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(139,92,246,0.12);">
                    <i data-lucide="store" style="color:#8B5CF6;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.TotalShops ?? 0)</div>
            <div class="sa-kpi-card__label">Tổng cửa hàng</div>
        </div>

        <div class="sa-kpi-card">
            <div class="sa-kpi-card__header">
                <div class="sa-kpi-card__icon" style="background:rgba(236,72,153,0.12);">
                    <i data-lucide="users" style="color:#EC4899;"></i>
                </div>
            </div>
            <div class="sa-kpi-card__value">@(_stats?.TotalUsers ?? 0)</div>
            <div class="sa-kpi-card__label">Tổng người dùng</div>
        </div>
    </div>

    @* ── RECENT MERCHANTS + SYSTEM HEALTH ── *@
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">

        @* Recent Merchants *@
        <div class="sa-panel">
            <div class="sa-panel__header">
                <h3 class="sa-panel__title">Doanh nghiệp gần đây</h3>
                <button class="sa-btn-outline" style="font-size:12px;padding:6px 12px;"
                        @onclick='() => NavigateTo("merchants")'>
                    Xem tất cả
                </button>
            </div>
            @if (_recentMerchants.Any())
            {
                <table class="sa-table">
                    <thead>
                        <tr>
                            <th>Tên doanh nghiệp</th>
                            <th>Trạng thái</th>
                            <th>Cửa hàng</th>
                            <th>Ngày tạo</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var m in _recentMerchants.Take(5))
                        {
                            <tr style="cursor:pointer;" @onclick="@(() => NavigationManager.NavigateTo($"/superadmin/merchants/{m.Id}"))">
                                <td>@m.BusinessName</td>
                                <td>
                                    <span class="sa-badge @GetStatusBadge(m.Status)">
                                        @GetStatusLabel(m.Status)
                                    </span>
                                </td>
                                <td>@m.ShopsCount</td>
                                <td>@m.CreatedAt.ToString("dd/MM/yyyy")</td>
                            </tr>
                        }
                    </tbody>
                </table>
            }
            else
            {
                <div class="sa-empty">
                    <div class="sa-empty__icon">
                        <i data-lucide="building-2" style="width:24px;height:24px;color:var(--sa-text-tertiary);"></i>
                    </div>
                    <p>Chưa có doanh nghiệp nào</p>
                </div>
            }
        </div>

        @* System Health *@
        <div class="sa-panel">
            <div class="sa-panel__header">
                <h3 class="sa-panel__title">Trạng thái hệ thống</h3>
                <button class="sa-btn-outline" style="font-size:12px;padding:6px 12px;"
                        @onclick="LoadHealthAsync">
                    <i data-lucide="refresh-cw" style="width:12px;height:12px;"></i>
                    Kiểm tra
                </button>
            </div>
            @if (_healthServices.Any())
            {
                <div class="sa-panel__body" style="display:flex;flex-direction:column;gap:8px;">
                    @foreach (var svc in _healthServices)
                    {
                        <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--sa-border-subtle);">
                            <div style="display:flex;align-items:center;gap:8px;">
                                <div style="width:8px;height:8px;border-radius:50%;background:@GetHealthColor(svc.Status);"></div>
                                <span style="font-size:13px;color:var(--sa-text-primary);">@svc.Name</span>
                            </div>
                            <div style="display:flex;align-items:center;gap:8px;">
                                @if (svc.ResponseTimeMs >= 0)
                                {
                                    <span style="font-size:11px;color:var(--sa-text-tertiary);">@(svc.ResponseTimeMs)ms</span>
                                }
                                <span class="sa-badge @GetHealthBadge(svc.Status)">@svc.Status</span>
                            </div>
                        </div>
                    }
                </div>
            }
            else if (_healthLoading)
            {
                <div class="sa-panel__body" style="text-align:center;padding:32px;">
                    <p style="color:var(--sa-text-tertiary);">Đang kiểm tra...</p>
                </div>
            }
            else
            {
                <div class="sa-empty">
                    <div class="sa-empty__icon">
                        <i data-lucide="activity" style="width:24px;height:24px;color:var(--sa-text-tertiary);"></i>
                    </div>
                    <p>Nhấn "Kiểm tra" để xem trạng thái</p>
                </div>
            }
        </div>
    </div>

    @* ── SUBSCRIPTION PLANS ── *@
    <div class="sa-panel">
        <div class="sa-panel__header">
            <h3 class="sa-panel__title">Gói đăng ký</h3>
            <button class="sa-btn-outline" style="font-size:12px;padding:6px 12px;"
                    @onclick='() => NavigateTo("subscriptions")'>
                Quản lý
            </button>
        </div>
        @if (_plans.Any())
        {
            <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(220px, 1fr));gap:16px;padding:20px;">
                @foreach (var plan in _plans)
                {
                    <div style="background:var(--sa-bg-interactive);border-radius:10px;padding:20px;">
                        <div style="font-size:15px;font-weight:700;color:var(--sa-text-primary);margin-bottom:4px;">@plan.Name</div>
                        <div style="font-size:12px;color:var(--sa-text-tertiary);margin-bottom:12px;">@plan.Description</div>
                        <div style="font-size:22px;font-weight:800;color:var(--sa-blue-light);">
                            @if (plan.PriceMonthly > 0)
                            {
                                @($"{plan.PriceMonthly:N0}đ")
                                <span style="font-size:12px;font-weight:400;color:var(--sa-text-tertiary);">/tháng</span>
                            }
                            else if (plan.Name == "Enterprise")
                            {
                                <span style="font-size:14px;">Liên hệ</span>
                            }
                            else
                            {
                                <span>Miễn phí</span>
                            }
                        </div>
                        <div style="margin-top:12px;font-size:12px;color:var(--sa-text-secondary);">
                            @plan.MaxShops cửa hàng • @plan.MaxStaff nhân viên
                        </div>
                    </div>
                }
            </div>
        }
    </div>
</div>

@code {
    private SuperAdminApiService.PlatformStatsDto? _stats;
    private List<SuperAdminApiService.MerchantAdminDto> _recentMerchants = new();
    private List<SuperAdminApiService.ServiceHealthDto> _healthServices = new();
    private List<SuperAdminApiService.SubscriptionPlanDto> _plans = new();
    private bool _healthLoading = false;

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

    private async Task LoadDataAsync()
    {
        IsLoading = true;
        StateHasChanged();

        var statsTask = Api.GetPlatformStatsAsync();
        var merchantsTask = Api.GetMerchantsAsync(1, 5);
        var plansTask = Api.GetPlansAsync();

        await Task.WhenAll(statsTask, merchantsTask, plansTask);

        _stats = statsTask.Result;
        _recentMerchants = merchantsTask.Result.Items;
        _plans = plansTask.Result;

        IsLoading = false;
        StateHasChanged();

        // EN: Load health in background (non-blocking)
        // VI: Load health ở background (không chặn)
        _ = LoadHealthAsync();
    }

    private async Task LoadHealthAsync()
    {
        _healthLoading = true;
        StateHasChanged();
        _healthServices = await Api.GetSystemHealthAsync();
        _healthLoading = false;
        StateHasChanged();
    }

    private static string GetStatusBadge(string? status) => status?.ToLowerInvariant() switch
    {
        "active" => "sa-badge--success",
        "pendingapproval" or "pending" => "sa-badge--warning",
        "suspended" => "sa-badge--danger",
        _ => "sa-badge--neutral"
    };

    private static string GetStatusLabel(string? status) => status?.ToLowerInvariant() switch
    {
        "active" => "Hoạt động",
        "pendingapproval" or "pending" => "Chờ duyệt",
        "suspended" => "Tạm ngưng",
        "inactive" => "Không hoạt động",
        _ => status ?? "—"
    };

    private static string GetHealthColor(string status) => status switch
    {
        "Healthy" => "#22C55E",
        "Degraded" => "#F59E0B",
        _ => "#EF4444"
    };

    private static string GetHealthBadge(string status) => status switch
    {
        "Healthy" => "sa-badge--success",
        "Degraded" => "sa-badge--warning",
        _ => "sa-badge--danger"
    };
}
