@page "/staff/dashboard"
@page "/staff"
@layout StaffLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject AuthService AuthSvc
@inject WebClientTpos.Client.Services.AuthStateService AuthState
@inject NavigationManager Nav
@inject IJSRuntime JS

@*
    EN: Staff dashboard — overview of today's status, quick actions.
    VI: Dashboard nhân viên — tổng quan trạng thái hôm nay, thao tác nhanh.
*@

<PageTitle>Staff Dashboard</PageTitle>

<div class="staff-page">
    <div class="staff-page-header">
        <h1 class="staff-page-title">Xin chào, @_displayName!</h1>
        <p class="staff-page-subtitle">@DateTime.Now.ToString("dddd, dd/MM/yyyy") &mdash; @(_profile?.Role ?? "Staff")</p>
    </div>

    @* ═══ QUICK ACTIONS ═══ *@
    <div style="display:flex;gap:12px;margin-bottom:24px;flex-wrap:wrap;">
        @if (!_checkedIn)
        {
            <button class="staff-btn-primary" @onclick="CheckIn" disabled="@_actionLoading">
                <i data-lucide="log-in"></i>
                Chấm công vào
            </button>
        }
        else if (!_checkedOut)
        {
            <button class="staff-btn-primary" @onclick="CheckOut" disabled="@_actionLoading" style="background:#F59E0B;">
                <i data-lucide="log-out"></i>
                Chấm công ra
            </button>
        }
        else
        {
            <span class="staff-status staff-status--success">Đã chấm công hôm nay</span>
        }

        <button class="staff-btn-secondary" @onclick="@(() => Nav.NavigateTo("/staff/leave"))">
            <i data-lucide="calendar-off"></i>
            Xin nghỉ phép
        </button>

        @if (_profile?.ShopId.HasValue == true)
        {
            <button class="staff-btn-primary" style="background:#FF5C00;" @onclick="@(() => Nav.NavigateTo($"/pos/{_profile.ShopId}/cafe"))">
                <i data-lucide="monitor"></i>
                Mở POS
            </button>
        }
    </div>

    @* ═══ STAT CARDS ═══ *@
    <div class="staff-stats-grid">
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(34,197,94,0.12);">
                <i data-lucide="clock" style="color:#22C55E;"></i>
            </div>
            <span class="staff-stat-card__value">@_todayHours</span>
            <span class="staff-stat-card__label">Giờ làm hôm nay</span>
        </div>
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(59,130,246,0.12);">
                <i data-lucide="calendar-check" style="color:#3B82F6;"></i>
            </div>
            <span class="staff-stat-card__value">@_monthDays</span>
            <span class="staff-stat-card__label">Ngày công tháng này</span>
        </div>
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(245,158,11,0.12);">
                <i data-lucide="calendar-off" style="color:#F59E0B;"></i>
            </div>
            <span class="staff-stat-card__value">@_leaveBalance</span>
            <span class="staff-stat-card__label">Ngày phép đã dùng</span>
        </div>
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(139,92,246,0.12);">
                <i data-lucide="bell" style="color:#8B5CF6;"></i>
            </div>
            <span class="staff-stat-card__value">@_unreadCount</span>
            <span class="staff-stat-card__label">Thông báo chưa đọc</span>
        </div>
    </div>

    @* ═══ RECENT ATTENDANCE ═══ *@
    <div class="staff-table-card">
        <div class="staff-table-card__header">
            <span class="staff-table-card__title">Chấm công gần đây</span>
            <button class="staff-btn-secondary" style="padding:6px 12px;font-size:13px;" @onclick="@(() => Nav.NavigateTo("/staff/attendance"))">
                Xem tất cả
            </button>
        </div>
        @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>Vào</th>
                        <th>Ra</th>
                        <th>Giờ làm</th>
                        <th>Trạng thái</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var r in _recentAttendance.Take(7))
                    {
                        <tr>
                            <td>@r.Date.ToString("dd/MM")</td>
                            <td>@(r.CheckIn?.ToLocalTime().ToString("HH:mm") ?? "--")</td>
                            <td>@(r.CheckOut?.ToLocalTime().ToString("HH:mm") ?? "--")</td>
                            <td>@(r.HoursWorked.HasValue ? r.HoursWorked.Value.ToString("0.#") + "h" : "--")</td>
                            <td>
                                <span class="staff-status @(r.Status == "Completed" ? "staff-status--success" : r.Status == "Working" ? "staff-status--info" : "staff-status--neutral")">
                                    @(r.Status == "Completed" ? "Hoàn thành" : r.Status == "Working" ? "Đang làm" : r.Status)
                                </span>
                            </td>
                        </tr>
                    }
                    @if (_recentAttendance.Count == 0)
                    {
                        <tr><td colspan="5" style="text-align:center;color:var(--admin-text-tertiary);padding:24px;">Chưa có dữ liệu chấm công</td></tr>
                    }
                </tbody>
            </MudSimpleTable>
        }
    </div>
</div>

@code {
    private PosDataService.StaffProfileInfo? _profile;
    private List<PosDataService.AttendanceRecord> _recentAttendance = new();
    private List<PosDataService.StaffNotification> _notifications = new();
    private bool _loading = true;
    private bool _actionLoading = false;
    private bool _checkedIn = false;
    private bool _checkedOut = false;
    private string _todayHours = "0";
    private int _monthDays = 0;
    // EN: Leave balance — loaded from real leave request data. TODO: load annual allowance from merchant config API.
    // VI: Số phép còn lại — tính từ dữ liệu nghỉ phép thực. TODO: tải số phép năm từ API cấu hình merchant.
    private int _leaveBalance = 0;
    private int _unreadCount = 0;

    private string _displayName => _profile?.FirstName ?? AuthState.UserEmail?.Split('@').FirstOrDefault() ?? "Staff";

    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 LoadDashboardData();
            StateHasChanged();
        }
    }

    private async Task LoadDashboardData()
    {
        try
        {
            var profileTask = DataService.GetMyStaffProfileAsync();
            var attendanceTask = DataService.GetMyAttendanceAsync();
            var notifTask = DataService.GetMyNotificationsAsync();

            await Task.WhenAll(profileTask, attendanceTask, notifTask);

            _profile = profileTask.Result;
            _recentAttendance = attendanceTask.Result;
            _notifications = notifTask.Result;

            _unreadCount = _notifications.Count(n => !n.IsRead);
            _monthDays = _recentAttendance.Count(r => r.Status == "Completed");

            // EN: Compare UTC dates consistently — backend stores all times in UTC.
            // VI: So sánh ngày UTC nhất quán — backend lưu tất cả thời gian theo UTC.
            var todayUtc = DateTime.UtcNow.Date;
            var today = _recentAttendance.FirstOrDefault(r => r.Date.Date == todayUtc);
            if (today != null)
            {
                _checkedIn = today.CheckIn.HasValue;
                _checkedOut = today.CheckOut.HasValue;
                if (today.CheckIn.HasValue && !today.CheckOut.HasValue)
                    _todayHours = ((DateTime.UtcNow - today.CheckIn.Value).TotalHours).ToString("0.#");
                else if (today.HoursWorked.HasValue)
                    _todayHours = today.HoursWorked.Value.ToString("0.#");
            }

            // EN: Calculate leave days used from approved leave requests (real data).
            // VI: Tính số ngày phép đã dùng từ các yêu cầu nghỉ phép đã duyệt (dữ liệu thực).
            try
            {
                var leaveRequests = await DataService.GetMyLeaveRequestsAsync();
                _leaveBalance = leaveRequests.Where(r => r.Status == "Approved").Sum(r => (r.EndDate - r.StartDate).Days + 1);
            }
            catch { }
        }
        catch { }
        finally { _loading = false; }
    }

    private async Task CheckIn()
    {
        _actionLoading = true;
        try
        {
            await DataService.PostAsync("api/bff/staff/me/attendance/check-in", new { });
            _checkedIn = true;
        }
        catch { }
        finally { _actionLoading = false; }
    }

    private async Task CheckOut()
    {
        _actionLoading = true;
        try
        {
            await DataService.PostAsync("api/bff/staff/me/attendance/check-out", new { });
            _checkedOut = true;
        }
        catch { }
        finally { _actionLoading = false; }
    }
}
