@page "/staff/attendance"
@layout StaffLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject AuthService AuthSvc
@inject IJSRuntime JS

@*
    EN: Staff attendance page — view check-in/check-out history.
    VI: Trang chấm công — xem lịch sử vào/ra.
*@

<PageTitle>Chấm công</PageTitle>

<div class="staff-page">
    <div class="staff-page-header">
        <h1 class="staff-page-title">Chấm công</h1>
        <p class="staff-page-subtitle">Lịch sử chấm công hàng ngày</p>
    </div>

    @* ═══ MONTH SELECTOR ═══ *@
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">
        <button class="staff-btn-secondary" style="padding:8px 12px;" @onclick="PrevMonth">
            <i data-lucide="chevron-left" style="width:16px;height:16px;"></i>
        </button>
        <span style="font-size:16px;font-weight:600;min-width:140px;text-align:center;">
            Tháng @_month/@_year
        </span>
        <button class="staff-btn-secondary" style="padding:8px 12px;" @onclick="NextMonth">
            <i data-lucide="chevron-right" style="width:16px;height:16px;"></i>
        </button>
    </div>

    @* ═══ SUMMARY ═══ *@
    <div class="staff-stats-grid" style="margin-bottom:20px;">
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_totalDays</span>
            <span class="staff-stat-card__label">Ngày công</span>
        </div>
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_totalHours.ToString("0.#")h</span>
            <span class="staff-stat-card__label">Tổng giờ làm</span>
        </div>
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@(_totalDays > 0 ? (_totalHours / _totalDays).ToString("0.#") : "0")h</span>
            <span class="staff-stat-card__label">TB giờ/ngày</span>
        </div>
    </div>

    @* ═══ TABLE ═══ *@
    <div class="staff-table-card">
        @if (_loading)
        {
            <div style="padding:32px;text-align:center;">
                <MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Success" />
            </div>
        }
        else
        {
            <MudSimpleTable Dense="true" Hover="true" Style="background:transparent;">
                <thead>
                    <tr>
                        <th>Ngày</th>
                        <th>Thứ</th>
                        <th>Vào</th>
                        <th>Ra</th>
                        <th>Giờ làm</th>
                        <th>Trạng thái</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var r in _records)
                    {
                        <tr>
                            <td>@r.Date.ToString("dd/MM/yyyy")</td>
                            <td>@GetDayOfWeek(r.Date)</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>
                                <span class="staff-status @GetStatusCss(r.Status)">
                                    @GetStatusLabel(r.Status)
                                </span>
                            </td>
                        </tr>
                    }
                    @if (_records.Count == 0)
                    {
                        <tr><td colspan="6" style="text-align:center;color:var(--admin-text-tertiary);padding:24px;">Không có dữ liệu</td></tr>
                    }
                </tbody>
            </MudSimpleTable>
        }
    </div>
</div>

@code {
    private List<PosDataService.AttendanceRecord> _records = new();
    private bool _loading = true;
    private int _month = DateTime.Now.Month;
    private int _year = DateTime.Now.Year;
    private int _totalDays = 0;
    private decimal _totalHours = 0;

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

        if (firstRender)
        {
            // EN: Restore auth session before loading data — token may not be in AuthState yet after forceLoad.
            // VI: Khôi phục session auth trước khi tải data — token có thể chưa có trong AuthState sau forceLoad.
            await AuthSvc.TryRestoreSessionAsync("staff");
            await LoadData();
            StateHasChanged();
        }
    }

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            _records = await DataService.GetMyAttendanceAsync(_month, _year);
            _records = _records.OrderByDescending(r => r.Date).ToList();
            _totalDays = _records.Count(r => r.Status == "Completed");
            _totalHours = _records.Where(r => r.HoursWorked.HasValue).Sum(r => r.HoursWorked!.Value);
        }
        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 static string GetDayOfWeek(DateTime d) => d.DayOfWeek switch
    {
        DayOfWeek.Monday => "T2",
        DayOfWeek.Tuesday => "T3",
        DayOfWeek.Wednesday => "T4",
        DayOfWeek.Thursday => "T5",
        DayOfWeek.Friday => "T6",
        DayOfWeek.Saturday => "T7",
        DayOfWeek.Sunday => "CN",
        _ => ""
    };

    private static string GetStatusCss(string? status) => status switch
    {
        "Completed" => "staff-status--success",
        "Working" => "staff-status--info",
        "Late" => "staff-status--warning",
        "Absent" => "staff-status--danger",
        _ => "staff-status--neutral"
    };

    private static string GetStatusLabel(string? status) => status switch
    {
        "Completed" => "Hoàn thành",
        "Working" => "Đang làm",
        "Late" => "Đi muộn",
        "Absent" => "Vắng mặt",
        _ => status ?? "--"
    };
}
