@page "/admin/shop/{ShopId}/attendance"
@layout AdminLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject IJSRuntime JS

@*
    EN: Admin shop attendance management — view all staff attendance.
    VI: Quản lý chấm công cửa hàng — xem chấm công tất cả nhân viên.
*@

<PageTitle>Chấm công - Quản lý</PageTitle>

<div style="padding:var(--admin-content-padding);">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;">
        <div>
            <h1 style="font-size:24px;font-weight:700;margin:0 0 4px;">Chấm công</h1>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0;">Quản lý chấm công nhân viên cửa hàng</p>
        </div>
        <div style="display:flex;align-items:center;gap:12px;">
            <button class="admin-btn-outline" @onclick="PrevMonth">
                <i data-lucide="chevron-left" style="width:16px;height:16px;"></i>
            </button>
            <span style="font-size:15px;font-weight:600;min-width:120px;text-align:center;">Tháng @_month/@_year</span>
            <button class="admin-btn-outline" @onclick="NextMonth">
                <i data-lucide="chevron-right" style="width:16px;height:16px;"></i>
            </button>
        </div>
    </div>

    @* ═══ SUMMARY CARDS ═══ *@
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;">
        <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-default);border-radius:var(--admin-radius-lg);padding:16px;">
            <div style="font-size:24px;font-weight:700;">@_staffCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Nhân viên</div>
        </div>
        <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-default);border-radius:var(--admin-radius-lg);padding:16px;">
            <div style="font-size:24px;font-weight:700;color:#22C55E;">@_presentToday</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Có mặt hôm nay</div>
        </div>
        <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-default);border-radius:var(--admin-radius-lg);padding:16px;">
            <div style="font-size:24px;font-weight:700;color:#F59E0B;">@_lateCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Đi muộn</div>
        </div>
        <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-default);border-radius:var(--admin-radius-lg);padding:16px;">
            <div style="font-size:24px;font-weight:700;color:#EF4444;">@_absentCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Vắng mặt</div>
        </div>
    </div>

    @* ═══ ATTENDANCE TABLE ═══ *@
    <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-default);border-radius:var(--admin-radius-lg);overflow:hidden;">
        @if (_loading)
        {
            <div style="padding:32px;text-align:center;">
                <MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Primary" />
            </div>
        }
        else
        {
            <MudSimpleTable Dense="true" Hover="true" Style="background:transparent;">
                <thead>
                    <tr>
                        <th>Nhân viên</th>
                        <th>Ngày</th>
                        <th>Vào</th>
                        <th>Ra</th>
                        <th>Giờ làm</th>
                        <th>Trạng thái</th>
                    </tr>
                </thead>
                <tbody>
                    @if (_records.Count == 0)
                    {
                        <tr><td colspan="6" style="text-align:center;color:var(--admin-text-tertiary);padding:24px;">Chưa có dữ liệu chấm công tháng này</td></tr>
                    }
                    @foreach (var r in _records)
                    {
                        <tr>
                            <td style="font-weight:600;">@(r.StaffName ?? r.StaffId.ToString()[..8])</td>
                            <td>@r.Date.ToString("dd/MM")</td>
                            <td style="color:#22C55E;">@(r.CheckIn?.ToLocalTime().ToString("HH:mm") ?? "--")</td>
                            <td style="color:#F59E0B;">@(r.CheckOut?.ToLocalTime().ToString("HH:mm") ?? "--")</td>
                            <td>@(r.HoursWorked.HasValue ? r.HoursWorked.Value.ToString("0.#") + "h" : "--")</td>
                            <td>
                                @{
                                    var css = r.Status switch { "Completed" => "color:#22C55E", "Working" => "color:#3B82F6", "Late" => "color:#F59E0B", "Absent" => "color:#EF4444", _ => "" };
                                }
                                <span style="font-size:12px;font-weight:600;@css">@r.Status</span>
                            </td>
                        </tr>
                    }
                </tbody>
            </MudSimpleTable>
        }
    </div>
</div>

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

    private List<AttendanceRow> _records = new();
    private bool _loading = true;
    private int _month = DateTime.Now.Month;
    private int _year = DateTime.Now.Year;
    private int _staffCount = 0;
    private int _presentToday = 0;
    private int _lateCount = 0;
    private int _absentCount = 0;

    protected override async Task OnInitializedAsync() => await LoadData();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try { await JS.InvokeVoidAsync("lucide.createIcons"); } catch { }
    }

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            if (Guid.TryParse(ShopId, out var shopGuid))
            {
                var staff = await DataService.GetStaffForShopAsync(shopGuid);
                _staffCount = staff.Count;

                // EN: Load real attendance data from merchant-service via BFF.
                // VI: Tải dữ liệu chấm công thực từ merchant-service qua BFF.
                var attendance = await DataService.GetListFromApiAsync<AttendanceRow>(
                    $"api/bff/shops/{shopGuid}/attendance?month={_month}&year={_year}");
                _records = attendance;

                var today = DateTime.UtcNow.Date;
                _presentToday = attendance.Count(a => a.Date.Date == today);
                _lateCount = attendance.Count(a => a.Date.Date == today && a.CheckIn.HasValue && a.CheckIn.Value.Hour >= 9);
                _absentCount = _staffCount - _presentToday;
            }
        }
        catch { }
        finally { _loading = false; }
    }

    private async Task PrevMonth()
    {
        _month--;
        if (_month < 1) { _month = 12; _year--; }
        await LoadData();
    }

    private async Task NextMonth()
    {
        if (_month == DateTime.Now.Month && _year == DateTime.Now.Year) return;
        _month++;
        if (_month > 12) { _month = 1; _year++; }
        await LoadData();
    }

    private record AttendanceRow(Guid StaffId, string? StaffName, DateTime Date, DateTime? CheckIn, DateTime? CheckOut, decimal? HoursWorked, string Status);
}
