@page "/admin/reports/staff"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject ISnackbar Snackbar
@inject IJSRuntime JS
@using WebClientTpos.Client.Services
@using System.Text

@*
    EN: Staff Performance Dashboard — orders handled, revenue, completion rates per staff member.
    VI: Trang hieu suat nhan vien — don xu ly, doanh thu, ty le hoan thanh theo nhan vien.
*@

<PageTitle>Hieu suat nhan vien — aPOS POS</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Hieu suat nhan vien</h1>
        <p class="admin-topbar__subtitle">Phan tich hieu qua lam viec cua nhan vien theo don hang va doanh thu</p>
    </div>
    <div class="admin-topbar__right" style="display:flex;align-items:center;gap:12px;">
        <MudDateRangePicker @bind-DateRange="_dateRange"
                            Label="Khoang thoi gian"
                            Variant="Variant.Outlined"
                            DateFormat="dd/MM/yyyy"
                            MaxDate="DateTime.Today"
                            Style="max-width:280px;"
                            Color="Color.Primary"
                            Class="mud-input-dark" />
        <MudButton Variant="Variant.Filled"
                   Color="Color.Primary"
                   OnClick="LoadDataAsync"
                   Disabled="_loading"
                   StartIcon="@Icons.Material.Filled.People">
            @if (_loading)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Surface" Class="mr-2" />
            }
            Xem hieu suat
        </MudButton>
        <MudButton Variant="Variant.Outlined"
                   Color="Color.Warning"
                   OnClick="ExportCsvAsync"
                   Disabled="_loading || _data == null"
                   StartIcon="@Icons.Material.Filled.Download">
            Xuat CSV
        </MudButton>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="admin-content" style="display:flex;flex-direction:column;gap:20px;">

    @if (_loading)
    {
        <div style="display:flex;justify-content:center;padding:48px;">
            <MudProgressCircular Size="Size.Large" Indeterminate="true" Color="Color.Primary" />
        </div>
    }
    else if (_data == null)
    {
        <MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
            Chon khoang thoi gian va nhan "Xem hieu suat" de tai du lieu hieu suat nhan vien.
        </MudAlert>
    }
    else
    {
        @* ── SUMMARY CARDS ── *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;">
            @* Best Performer *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(245,158,11,0.1);">
                    <i data-lucide="trophy" style="color:#F59E0B;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@(_bestPerformer?.StaffName ?? "N/A")</span>
                    <span class="admin-stat-card__label">Nhan vien xuat sac nhat</span>
                    @if (_bestPerformer != null)
                    {
                        <span style="font-size:12px;color:var(--admin-text-tertiary);">@FormatVND(_bestPerformer.TotalRevenue) doanh thu</span>
                    }
                </div>
            </div>
            @* Total Staff *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);">
                    <i data-lucide="users" style="color:#3B82F6;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_data.Staff.Count</span>
                    <span class="admin-stat-card__label">Tong nhan vien</span>
                </div>
            </div>
            @* Average Completion Rate *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);">
                    <i data-lucide="check-circle" style="color:#22C55E;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@(_data.ShopAverage.CompletionRate.ToString("F1"))%</span>
                    <span class="admin-stat-card__label">Ty le hoan thanh TB</span>
                </div>
            </div>
            @* Average Handling Time *@
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(139,92,246,0.1);">
                    <i data-lucide="clock" style="color:#8B5CF6;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@(_data.ShopAverage.AverageHandlingTimeMinutes.ToString("F1")) phut</span>
                    <span class="admin-stat-card__label">Thoi gian xu ly TB</span>
                </div>
            </div>
        </div>

        @* ── STAFF REVENUE COMPARISON CHART ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">So sanh doanh thu nhan vien</h3>
            </div>
            <div class="admin-panel__body">
                @if (_revenueChartSeries.Any())
                {
                    <MudChart ChartType="ChartType.Bar"
                              ChartSeries="@_revenueChartSeries"
                              XAxisLabels="@_revenueChartLabels"
                              Width="100%"
                              Height="300px"
                              ChartOptions="_barOptions" />
                }
                else
                {
                    <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);">Khong co du lieu de so sanh.</div>
                }
            </div>
        </div>

        @* ── STAFF PERFORMANCE TABLE ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">Chi tiet hieu suat nhan vien</h3>
            </div>
            <div class="admin-panel__body" style="padding:0;">
                <MudTable Items="@_data.Staff"
                          Dense="true"
                          Hover="true"
                          Striped="true"
                          Elevation="0"
                          SortLabel="Sap xep theo"
                          Class="mud-table-dark">
                    <HeaderContent>
                        <MudTh><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.StaffName)">Nhan vien</MudTableSortLabel></MudTh>
                        <MudTh Style="text-align:right;"><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.OrdersHandled)" InitialDirection="SortDirection.Descending">Don xu ly</MudTableSortLabel></MudTh>
                        <MudTh Style="text-align:right;"><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.TotalRevenue)">Doanh thu</MudTableSortLabel></MudTh>
                        <MudTh Style="text-align:right;"><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.AverageOrderValue)">GT TB / don</MudTableSortLabel></MudTh>
                        <MudTh Style="text-align:right;"><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.CompletionRate)">Ty le HT</MudTableSortLabel></MudTh>
                        <MudTh Style="text-align:right;"><MudTableSortLabel SortBy="new Func<PosDataService.StaffMetricsInfo, object>(x => x.AverageHandlingTimeMinutes)">TG xu ly TB</MudTableSortLabel></MudTh>
                    </HeaderContent>
                    <RowTemplate>
                        <MudTd Style="@GetRowStyle(context)">
                            <div style="display:flex;align-items:center;gap:8px;">
                                @if (context == _bestPerformer)
                                {
                                    <i data-lucide="trophy" style="color:#F59E0B;width:16px;height:16px;"></i>
                                }
                                <span style="font-weight:600;">@context.StaffName</span>
                            </div>
                        </MudTd>
                        <MudTd Style="@($"text-align:right;font-weight:600;{GetRowStyle(context)}")">@context.OrdersHandled</MudTd>
                        <MudTd Style="@($"text-align:right;font-weight:700;color:var(--admin-orange-primary);{GetRowStyle(context)}")">@FormatVND(context.TotalRevenue)</MudTd>
                        <MudTd Style="@($"text-align:right;{GetRowStyle(context)}")">@FormatVND(context.AverageOrderValue)</MudTd>
                        <MudTd Style="@($"text-align:right;{GetRowStyle(context)}")">
                            <MudChip T="string"
                                     Size="Size.Small"
                                     Color="@(context.CompletionRate >= 90 ? Color.Success : context.CompletionRate >= 70 ? Color.Warning : Color.Error)"
                                     Variant="Variant.Filled">
                                @context.CompletionRate.ToString("F1")%
                            </MudChip>
                        </MudTd>
                        <MudTd Style="@($"text-align:right;{GetRowStyle(context)}")">@context.AverageHandlingTimeMinutes.ToString("F1") phut</MudTd>
                    </RowTemplate>
                    <FooterContent>
                        <MudTh Style="font-weight:700;color:var(--admin-text-secondary);">Trung binh cua hang</MudTh>
                        <MudTh Style="text-align:right;font-weight:700;">@_data.ShopAverage.OrdersHandled</MudTh>
                        <MudTh Style="text-align:right;font-weight:700;color:var(--admin-orange-primary);">@FormatVND(_data.ShopAverage.TotalRevenue)</MudTh>
                        <MudTh Style="text-align:right;font-weight:700;">@FormatVND(_data.ShopAverage.AverageOrderValue)</MudTh>
                        <MudTh Style="text-align:right;font-weight:700;">@_data.ShopAverage.CompletionRate.ToString("F1")%</MudTh>
                        <MudTh Style="text-align:right;font-weight:700;">@_data.ShopAverage.AverageHandlingTimeMinutes.ToString("F1") phut</MudTh>
                    </FooterContent>
                </MudTable>
            </div>
        </div>
    }
</div>

@code {
    // EN: Date range for the report / VI: Khoang thoi gian cho bao cao
    private DateRange _dateRange = new(DateTime.Today.AddDays(-30), DateTime.Today);
    private bool _loading = false;
    private PosDataService.StaffPerformanceInfo? _data;
    private PosDataService.StaffMetricsInfo? _bestPerformer;

    // EN: Chart data / VI: Du lieu bieu do
    private List<ChartSeries> _revenueChartSeries = new();
    private string[] _revenueChartLabels = Array.Empty<string>();

    private ChartOptions _barOptions = new()
    {
        ChartPalette = new[] { "#FF5C00", "#22C55E" },
        YAxisTicks = 5
    };

    /// <summary>
    /// EN: Get the current shop ID from query string context.
    /// VI: Lay shop ID hien tai tu query string context.
    /// </summary>
    private Guid? GetCurrentShopId()
    {
        var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
        if (Guid.TryParse(query["shopId"], out var qsShopId))
            return qsShopId;
        return null;
    }

    /// <summary>
    /// EN: Load staff performance data.
    /// VI: Tai du lieu hieu suat nhan vien.
    /// </summary>
    private async Task LoadDataAsync()
    {
        var shopId = GetCurrentShopId();
        if (!shopId.HasValue)
        {
            Snackbar.Add("Vui long chon shop truoc khi xem bao cao.", Severity.Warning);
            return;
        }

        if (_dateRange.Start == null || _dateRange.End == null)
        {
            Snackbar.Add("Vui long chon khoang thoi gian.", Severity.Warning);
            return;
        }

        _loading = true;
        _data = null;
        _bestPerformer = null;
        StateHasChanged();

        try
        {
            _data = await DataService.GetStaffPerformanceAsync(
                shopId.Value,
                _dateRange.Start.Value,
                _dateRange.End.Value);

            if (_data != null)
            {
                _bestPerformer = _data.Staff.OrderByDescending(s => s.TotalRevenue).FirstOrDefault();
                BuildChartData();
                Snackbar.Add("Da tai hieu suat nhan vien thanh cong.", Severity.Success);
            }
            else
            {
                Snackbar.Add("Khong the tai du lieu. Vui long thu lai.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Build chart data from staff performance data.
    /// VI: Xay dung du lieu bieu do tu du lieu hieu suat nhan vien.
    /// </summary>
    private void BuildChartData()
    {
        if (_data == null || !_data.Staff.Any())
        {
            _revenueChartLabels = Array.Empty<string>();
            _revenueChartSeries = new();
            return;
        }

        var orderedStaff = _data.Staff.OrderByDescending(s => s.TotalRevenue).Take(10).ToList();
        _revenueChartLabels = orderedStaff.Select(s => s.StaffName).ToArray();
        _revenueChartSeries = new List<ChartSeries>
        {
            new ChartSeries { Name = "Doanh thu", Data = orderedStaff.Select(s => (double)s.TotalRevenue).ToArray() },
            new ChartSeries { Name = "Don hang", Data = orderedStaff.Select(s => (double)s.OrdersHandled).ToArray() }
        };
    }

    /// <summary>
    /// EN: Get row style color-coded by completion rate: green (>=90%), yellow (70-89%), red (<70%).
    /// VI: Lay style dong theo ma mau ty le hoan thanh: xanh (>=90%), vang (70-89%), do (<70%).
    /// </summary>
    private string GetRowStyle(PosDataService.StaffMetricsInfo staff)
    {
        if (staff.CompletionRate >= 90)
            return "background:rgba(34,197,94,0.06);";
        if (staff.CompletionRate >= 70)
            return "background:rgba(245,158,11,0.06);";
        return "background:rgba(239,68,68,0.06);";
    }

    /// <summary>
    /// EN: Export staff performance data to CSV and trigger browser download.
    /// VI: Xuat du lieu hieu suat nhan vien sang CSV va kich hoat tai xuong tren trinh duyet.
    /// </summary>
    private async Task ExportCsvAsync()
    {
        if (_data == null || !_data.Staff.Any())
        {
            Snackbar.Add("Khong co du lieu de xuat.", Severity.Warning);
            return;
        }

        try
        {
            var sb = new StringBuilder();
            sb.AppendLine("Nhan vien,Don xu ly,Doanh thu,GT TB / don,Hoan thanh,Da huy,Ty le HT (%),TG xu ly TB (phut)");
            foreach (var s in _data.Staff)
            {
                sb.AppendLine($"\"{s.StaffName}\",{s.OrdersHandled},{s.TotalRevenue:F0},{s.AverageOrderValue:F0},{s.CompletedOrders},{s.CancelledOrders},{s.CompletionRate:F1},{s.AverageHandlingTimeMinutes:F1}");
            }

            var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(sb.ToString())).ToArray();
            var base64 = Convert.ToBase64String(bytes);
            var fileName = $"hieu-suat-nhan-vien_{_dateRange.Start:yyyyMMdd}_{_dateRange.End:yyyyMMdd}.csv";

            // EN: Use JS interop to trigger download / VI: Dung JS interop de kich hoat tai xuong
            await JS.InvokeVoidAsync("eval", $@"
                var link = document.createElement('a');
                link.href = 'data:text/csv;base64,{base64}';
                link.download = '{fileName}';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            ");

            Snackbar.Add($"Da xuat file {fileName}.", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Loi khi xuat CSV: {ex.Message}", Severity.Error);
        }
    }

    private static string FormatVND(decimal val) => val.ToString("N0") + " d";
}
