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

@*
    EN: Staff leave request page — view/create leave requests.
    VI: Trang nghỉ phép — xem/tạo yêu cầu nghỉ phép.
*@

<PageTitle>Nghỉ phép</PageTitle>

<div class="staff-page">
    <div class="staff-page-header" style="display:flex;align-items:center;justify-content:space-between;">
        <div>
            <h1 class="staff-page-title">Nghỉ phép</h1>
            <p class="staff-page-subtitle">Quản lý yêu cầu nghỉ phép</p>
        </div>
        <button class="staff-btn-primary" @onclick="ShowCreateForm">
            <i data-lucide="plus"></i>
            Xin nghỉ phép
        </button>
    </div>

    @* ═══ SUMMARY ═══ *@
    @* EN: Leave stats from real data. Total annual allowance will come from merchant config API (TODO).
       VI: Thống kê phép từ dữ liệu thực. Tổng phép năm sẽ từ API cấu hình merchant (TODO). *@
    <div class="staff-stats-grid" style="margin-bottom:20px;">
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_usedDays</span>
            <span class="staff-stat-card__label">Ngày phép đã dùng</span>
        </div>
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_pendingCount</span>
            <span class="staff-stat-card__label">Chờ duyệt</span>
        </div>
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_rejectedCount</span>
            <span class="staff-stat-card__label">Từ chối</span>
        </div>
        <div class="staff-stat-card">
            <span class="staff-stat-card__value">@_requests.Count</span>
            <span class="staff-stat-card__label">Tổng yêu cầu</span>
        </div>
    </div>

    @* ═══ CREATE FORM ═══ *@
    @if (_showForm)
    {
        <div class="staff-table-card" style="margin-bottom:20px;padding:20px;">
            <h3 style="font-size:16px;font-weight:600;margin:0 0 16px;">Tạo yêu cầu nghỉ phép</h3>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <MudSelect T="string" @bind-Value="_leaveType" Label="Loại nghỉ phép" Variant="Variant.Outlined" Dense="true">
                    <MudSelectItem Value="@("Annual")">Phép năm</MudSelectItem>
                    <MudSelectItem Value="@("Sick")">Nghỉ ốm</MudSelectItem>
                    <MudSelectItem Value="@("Personal")">Việc cá nhân</MudSelectItem>
                    <MudSelectItem Value="@("Maternity")">Thai sản</MudSelectItem>
                    <MudSelectItem Value="@("Other")">Khác</MudSelectItem>
                </MudSelect>
                <div></div>
                <MudDatePicker @bind-Date="_startDate" Label="Từ ngày" Variant="Variant.Outlined" />
                <MudDatePicker @bind-Date="_endDate" Label="Đến ngày" Variant="Variant.Outlined" />
            </div>
            <MudTextField @bind-Value="_reason" Label="Lý do" Variant="Variant.Outlined" Lines="2" Style="margin-top:16px;" />
            <div style="display:flex;gap:12px;margin-top:16px;">
                <button class="staff-btn-primary" @onclick="SubmitLeave" disabled="@_submitting">
                    @(_submitting ? "Đang gửi..." : "Gửi yêu cầu")
                </button>
                <button class="staff-btn-secondary" @onclick="@(() => _showForm = false)">Hủy</button>
            </div>
        </div>
    }

    @* ═══ LEAVE LIST ═══ *@
    <div class="staff-table-card">
        <div class="staff-table-card__header">
            <span class="staff-table-card__title">Lịch sử nghỉ phép</span>
        </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>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>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var r in _requests)
                    {
                        <tr>
                            <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:200px;overflow:hidden;text-overflow:ellipsis;">@(r.Reason ?? "--")</td>
                            <td>
                                <span class="staff-status @GetLeaveStatusCss(r.Status)">
                                    @GetLeaveStatusLabel(r.Status)
                                </span>
                            </td>
                        </tr>
                    }
                    @if (_requests.Count == 0)
                    {
                        <tr><td colspan="6" style="text-align:center;color:var(--admin-text-tertiary);padding:24px;">Chưa có yêu cầu nghỉ phép nào</td></tr>
                    }
                </tbody>
            </MudSimpleTable>
        }
    </div>
</div>

@code {
    private List<PosDataService.LeaveRequest> _requests = new();
    private bool _loading = true;
    private bool _showForm = false;
    private bool _submitting = false;
    private int _usedDays = 0;
    private int _pendingCount = 0;
    private int _rejectedCount = 0;

    // Form fields
    private string _leaveType = "Annual";
    private DateTime? _startDate;
    private DateTime? _endDate;
    private string _reason = "";

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

    private async Task LoadLeaveRequests()
    {
        _loading = true;
        try
        {
            _requests = await DataService.GetMyLeaveRequestsAsync();
            _usedDays = _requests.Where(r => r.Status == "Approved").Sum(r => (r.EndDate - r.StartDate).Days + 1);
            _pendingCount = _requests.Count(r => r.Status == "Pending");
            _rejectedCount = _requests.Count(r => r.Status == "Rejected");
        }
        catch { }
        finally { _loading = false; }
    }

    private void ShowCreateForm()
    {
        _showForm = true;
        _startDate = DateTime.Now.Date.AddDays(1);
        _endDate = DateTime.Now.Date.AddDays(1);
        _reason = "";
        _leaveType = "Annual";
    }

    private async Task SubmitLeave()
    {
        if (_startDate == null || _endDate == null)
        {
            Snackbar.Add("Vui lòng chọn ngày", Severity.Warning);
            return;
        }
        _submitting = true;
        try
        {
            await DataService.PostAsync("api/bff/staff/me/leave-requests", new
            {
                leaveType = _leaveType,
                startDate = _startDate.Value.ToString("o"),
                endDate = _endDate.Value.ToString("o"),
                reason = _reason
            });
            Snackbar.Add("Đã gửi yêu cầu nghỉ phép", Severity.Success);
            _showForm = false;
            _requests = await DataService.GetMyLeaveRequestsAsync();
        }
        catch
        {
            Snackbar.Add("Gửi yêu cầu thất bại", Severity.Error);
        }
        finally { _submitting = false; }
    }

    private static string GetLeaveTypeLabel(string type) => type switch
    {
        "Annual" => "Phép năm",
        "Sick" => "Nghỉ ốm",
        "Personal" => "Việc cá nhân",
        "Maternity" => "Thai sản",
        _ => type
    };

    private static string GetLeaveStatusCss(string status) => status switch
    {
        "Approved" => "staff-status--success",
        "Pending" => "staff-status--warning",
        "Rejected" => "staff-status--danger",
        _ => "staff-status--neutral"
    };

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