@page "/admin/shop/{ShopId}/leave-requests"
@layout AdminLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject IJSRuntime JS
@inject ISnackbar Snackbar

@*
    EN: Admin leave request management — approve/reject staff leave requests.
    VI: Quản lý nghỉ phép — duyệt/từ chối yêu cầu nghỉ phép nhân viên.
*@

<PageTitle>Nghỉ phép - 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;">Quản lý nghỉ phép</h1>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0;">Duyệt và quản lý yêu cầu nghỉ phép nhân viên</p>
        </div>
    </div>

    @* ═══ SUMMARY ═══ *@
    <div style="display:grid;grid-template-columns:repeat(3,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;color:#F59E0B;">@_pendingCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Chờ duyệt</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;">@_approvedCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Đã duyệt</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;">@_rejectedCount</div>
            <div style="font-size:13px;color:var(--admin-text-tertiary);">Từ chối</div>
        </div>
    </div>

    @* ═══ LEAVE REQUESTS 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 if (_requests.Count == 0)
        {
            <div style="padding:48px;text-align:center;color:var(--admin-text-tertiary);">
                Chưa có yêu cầu nghỉ phép nào
            </div>
        }
        else
        {
            <MudSimpleTable Dense="true" Hover="true" Style="background:transparent;">
                <thead>
                    <tr>
                        <th>Nhân viên</th>
                        <th>Loại</th>
                        <th>Từ ngày</th>
                        <th>Đến ngày</th>
                        <th>Số ngày</th>
                        <th>Lý do</th>
                        <th>Trạng thái</th>
                        <th>Thao tác</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var r in _requests)
                    {
                        <tr>
                            <td style="font-weight:600;">@r.StaffId.ToString()[..8]...</td>
                            <td>@GetLeaveTypeLabel(r.LeaveType)</td>
                            <td>@r.StartDate.ToString("dd/MM/yyyy")</td>
                            <td>@r.EndDate.ToString("dd/MM/yyyy")</td>
                            <td>@((r.EndDate - r.StartDate).Days + 1)</td>
                            <td style="max-width:150px;overflow:hidden;text-overflow:ellipsis;">@(r.Reason ?? "--")</td>
                            <td>
                                @{
                                    var statusCss = r.Status switch { "Approved" => "color:#22C55E", "Pending" => "color:#F59E0B", "Rejected" => "color:#EF4444", _ => "" };
                                }
                                <span style="font-size:12px;font-weight:600;@statusCss">@GetStatusLabel(r.Status)</span>
                            </td>
                            <td>
                                @if (r.Status == "Pending")
                                {
                                    <div style="display:flex;gap:6px;">
                                        <button style="background:#22C55E;color:white;border:none;border-radius:6px;padding:4px 10px;font-size:12px;font-weight:600;cursor:pointer;" @onclick="@(() => Approve(r))">Duyệt</button>
                                        <button style="background:#EF4444;color:white;border:none;border-radius:6px;padding:4px 10px;font-size:12px;font-weight:600;cursor:pointer;" @onclick="@(() => Reject(r))">Từ chối</button>
                                    </div>
                                }
                            </td>
                        </tr>
                    }
                </tbody>
            </MudSimpleTable>
        }
    </div>
</div>

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

    private List<PosDataService.LeaveRequest> _requests = new();
    private bool _loading = true;
    private int _pendingCount = 0;
    private int _approvedCount = 0;
    private int _rejectedCount = 0;

    protected override async Task OnInitializedAsync()
    {
        await LoadLeaveRequests();
    }

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

    private async Task LoadLeaveRequests()
    {
        _loading = true;
        try
        {
            _requests = await DataService.GetListFromApiAsync<PosDataService.LeaveRequest>($"api/bff/shops/{ShopId}/leave-requests");
            _pendingCount = _requests.Count(r => r.Status == "Pending");
            _approvedCount = _requests.Count(r => r.Status == "Approved");
            _rejectedCount = _requests.Count(r => r.Status == "Rejected");
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Lỗi tải danh sách nghỉ phép: {ex.Message}", Severity.Error);
        }
        _loading = false;
    }

    private async Task Approve(PosDataService.LeaveRequest r)
    {
        try
        {
            // EN: BFF extracts approver userId from JWT — no need to send from client.
            // VI: BFF trích userId người duyệt từ JWT — không cần gửi từ client.
            var ok = await DataService.PostAsync($"api/bff/leave-requests/{r.Id}/approve", new { });
            if (ok)
            {
                Snackbar.Add("Đã duyệt yêu cầu nghỉ phép", Severity.Success);
                await LoadLeaveRequests();
            }
            else
                Snackbar.Add("Không thể duyệt yêu cầu", Severity.Error);
        }
        catch (Exception ex) { Snackbar.Add($"Lỗi: {ex.Message}", Severity.Error); }
    }

    private async Task Reject(PosDataService.LeaveRequest r)
    {
        try
        {
            // EN: BFF extracts rejector userId from JWT — only send reason from client.
            // VI: BFF trích userId người từ chối từ JWT — chỉ gửi lý do từ client.
            var ok = await DataService.PostAsync($"api/bff/leave-requests/{r.Id}/reject",
                new { reason = "Không được duyệt" });
            if (ok)
            {
                Snackbar.Add("Đã từ chối yêu cầu nghỉ phép", Severity.Warning);
                await LoadLeaveRequests();
            }
            else
                Snackbar.Add("Không thể từ chối yêu cầu", Severity.Error);
        }
        catch (Exception ex) { Snackbar.Add($"Lỗi: {ex.Message}", Severity.Error); }
    }

    private static string GetLeaveTypeLabel(string t) => t switch
    {
        "Annual" => "Phép năm",
        "Sick" => "Nghỉ ốm",
        "Personal" => "Cá nhân",
        _ => t
    };

    private static string GetStatusLabel(string s) => s switch
    {
        "Approved" => "Đã duyệt",
        "Pending" => "Chờ duyệt",
        "Rejected" => "Từ chối",
        _ => s
    };
}
