@page "/admin/system/audit"
@layout AdminLayout
@inherits AdminBase
@inject WebClientTpos.Client.Services.IamApiService IamService
@using WebClientTpos.Client.Services

@*
    EN: Audit log — real audit log data from IAM Service.
    VI: Nhật ký hệ thống — dữ liệu audit log thật từ IAM Service.
*@

<PageTitle>Nhật ký hệ thống — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Nhật ký hệ thống</h1>
        <p class="admin-topbar__subtitle">Lịch sử thao tác & sự kiện hệ thống</p>
    </div>
    <div class="admin-topbar__right">
        <div class="admin-search" style="width:220px;">
            <i data-lucide="search"></i>
            <input type="text" placeholder="Tìm trong log..." @bind="SearchQuery" @bind:event="oninput" />
        </div>
        <button class="admin-btn-secondary">
            <i data-lucide="refresh-cw"></i>
            <span>Làm mới</span>
        </button>
    </div>
</div>

@* ═══ TABS ═══ *@
<div class="admin-tabs">
    <button class="admin-tab @(_activeTab == "all" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "all")">
        Tất cả <span class="admin-tab__badge admin-tab__badge--active">@_logs.Count</span>
    </button>
    <button class="admin-tab @(_activeTab == "auth" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "auth")">
        Xác thực <span class="admin-tab__badge">@_logs.Count(l => IsCategory(l, "auth"))</span>
    </button>
    <button class="admin-tab @(_activeTab == "config" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "config")">
        Cấu hình <span class="admin-tab__badge">@_logs.Count(l => IsCategory(l, "config"))</span>
    </button>
    <button class="admin-tab @(_activeTab == "data" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "data")">
        Dữ liệu <span class="admin-tab__badge">@_logs.Count(l => IsCategory(l, "data"))</span>
    </button>
</div>

@* ═══ CONTENT ═══ *@
@if (_loading)
{
    <div class="admin-content" style="display:flex;align-items:center;justify-content:center;min-height:300px;">
        <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
    </div>
}
else if (!FilteredLogs.Any())
{
    <div class="admin-content" style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:300px;gap:12px;">
        <i data-lucide="file-text" style="width:48px;height:48px;color:var(--admin-text-tertiary);"></i>
        <span style="color:var(--admin-text-tertiary);font-size:15px;">Chưa có log nào</span>
        <span style="color:var(--admin-text-tertiary);font-size:13px;">Log sẽ xuất hiện khi có hoạt động trong hệ thống</span>
    </div>
}
else
{
    <div class="admin-content" style="display:flex;flex-direction:column;gap:0;">
        <div class="admin-panel" style="flex:1;">
            <div class="admin-panel__body" style="padding:0;">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Thời gian</th>
                            <th>Người dùng</th>
                            <th>Hành động</th>
                            <th>Tài nguyên</th>
                            <th>IP</th>
                            <th>Trạng thái</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var log in FilteredLogs)
                        {
                            <tr>
                                <td style="font-size:12px;color:var(--admin-text-tertiary);white-space:nowrap;">@FormatTime(log.Timestamp)</td>
                                <td>
                                    <div style="display:flex;align-items:center;gap:8px;">
                                        <div class="admin-user-avatar" style="width:28px;height:28px;font-size:10px;background-color:#8B5CF6;">
                                            @GetInitials(log.ActorEmail ?? log.ActorId ?? "?")
                                        </div>
                                        <span style="font-weight:500;">@(log.ActorEmail ?? log.ActorId ?? "System")</span>
                                    </div>
                                </td>
                                <td>
                                    <div style="display:flex;align-items:center;gap:6px;">
                                        <i data-lucide="@GetEventIcon(log.EventType)" style="width:14px;height:14px;color:@GetEventColor(log.EventType);"></i>
                                        <span>@(log.EventType ?? "—")</span>
                                    </div>
                                </td>
                                <td style="color:var(--admin-text-secondary);">@(log.ResourceType ?? "—") @(log.ResourceId != null ? $"#{log.ResourceId[..Math.Min(8, log.ResourceId.Length)]}" : "")</td>
                                <td style="font-size:12px;color:var(--admin-text-tertiary);font-family:monospace;">@(log.IpAddress ?? "—")</td>
                                <td>
                                    <div class="admin-status-badge @(log.Success?.ToString() == "Success" ? "admin-status-badge--online" : "admin-status-badge--offline")">
                                        <span class="admin-status-badge__dot"></span>
                                        @(log.Success?.ToString() == "Success" ? "Thành công" : log.Success?.ToString() ?? "—")
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
}

@code {
    private bool _loading = true;
    private string _activeTab = "all";
    private List<IamApiService.AuditLogDto> _logs = new();

    private IEnumerable<IamApiService.AuditLogDto> FilteredLogs
    {
        get
        {
            var list = _activeTab == "all" ? _logs.AsEnumerable() : _logs.Where(l => IsCategory(l, _activeTab));
            if (!string.IsNullOrEmpty(SearchQuery))
                list = list.Where(l => (l.EventType ?? "").Contains(SearchQuery, StringComparison.OrdinalIgnoreCase)
                    || (l.ActorEmail ?? "").Contains(SearchQuery, StringComparison.OrdinalIgnoreCase)
                    || (l.ResourceType ?? "").Contains(SearchQuery, StringComparison.OrdinalIgnoreCase));
            return list;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        try { _logs = await IamService.GetAuditLogsAsync(); }
        catch { _logs = new(); }
        finally { _loading = false; }
    }

    private static bool IsCategory(IamApiService.AuditLogDto log, string cat)
    {
        var evt = (log.EventType ?? "").ToLower();
        return cat switch
        {
            "auth" => evt.Contains("login") || evt.Contains("auth") || evt.Contains("token") || evt.Contains("password"),
            "config" => evt.Contains("config") || evt.Contains("setting") || evt.Contains("role") || evt.Contains("permission"),
            "data" => evt.Contains("create") || evt.Contains("update") || evt.Contains("delete") || evt.Contains("order"),
            _ => true
        };
    }

    private static string FormatTime(DateTime? dt) => dt?.ToString("dd/MM/yyyy HH:mm:ss") ?? "—";

    private static string GetInitials(string v)
    {
        if (v.Contains('@')) v = v.Split('@')[0];
        return v.Length >= 2 ? v[..2].ToUpper() : v.ToUpper();
    }

    private static string GetEventIcon(string? eventType) => (eventType ?? "").ToLower() switch
    {
        var e when e.Contains("login") => "log-in",
        var e when e.Contains("create") => "plus-circle",
        var e when e.Contains("update") => "edit",
        var e when e.Contains("delete") => "trash-2",
        var e when e.Contains("role") => "shield",
        _ => "activity"
    };

    private static string GetEventColor(string? eventType) => (eventType ?? "").ToLower() switch
    {
        var e when e.Contains("login") => "#22C55E",
        var e when e.Contains("create") => "#3B82F6",
        var e when e.Contains("update") => "#F59E0B",
        var e when e.Contains("delete") => "#EF4444",
        _ => "#8B5CF6"
    };
}
