@*
    EN: Stock Overview — Admin page showing all products with stock levels, color-coded rows,
        search/filter, low stock threshold settings, and summary cards.
    VI: Tong quan ton kho — Trang admin hien thi tat ca san pham voi muc ton kho, hang ma mau,
        tim kiem/loc, cai dat nguong ton kho thap, va the tom tat.
*@
@page "/admin/store/{ShopId:guid}/stock"
@layout AdminLayout
@inherits AdminBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject ISnackbar Snackbar
@inject IDialogService DialogService

<div style="padding:0;">
    @* ═══ HEADER / TIEU DE ═══ *@
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
        <div>
            <h2 style="margin:0;font-size:22px;font-weight:700;color:var(--admin-text-primary, #FFF);">
                <i data-lucide="warehouse" style="width:22px;height:22px;margin-right:8px;color:var(--admin-orange-primary);display:inline;"></i>
                Tong quan ton kho
            </h2>
            <p style="margin:4px 0 0;font-size:13px;color:var(--admin-text-tertiary);">
                Theo doi muc ton kho va canh bao het hang
            </p>
        </div>
        <button @onclick="RefreshData"
                style="padding:8px 16px;background:var(--admin-orange-primary);color:#FFF;border:none;border-radius:8px;
                       font-size:13px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:6px;">
            <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i> Lam moi
        </button>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;padding:60px;">
            <MudProgressCircular Indeterminate="true" Color="Color.Warning" />
        </div>
    }
    else
    {
        @* ═══ SUMMARY CARDS / THE TOM TAT ═══ *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-bottom:20px;">
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);">
                    <i data-lucide="package" style="color:#3B82F6;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_totalProducts</span>
                    <span class="admin-stat-card__label">Tong san pham</span>
                </div>
            </div>
            <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">@_inStockCount</span>
                    <span class="admin-stat-card__label">Con hang</span>
                </div>
            </div>
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(245,158,11,0.1);">
                    <i data-lucide="alert-triangle" style="color:#F59E0B;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_lowStockCount</span>
                    <span class="admin-stat-card__label">Sap het</span>
                </div>
            </div>
            <div class="admin-stat-card">
                <div class="admin-stat-card__icon" style="background:rgba(239,68,68,0.1);">
                    <i data-lucide="x-circle" style="color:#EF4444;"></i>
                </div>
                <div class="admin-stat-card__content">
                    <span class="admin-stat-card__value">@_outOfStockCount</span>
                    <span class="admin-stat-card__label">Het hang</span>
                </div>
            </div>
        </div>

        @* ═══ SEARCH & FILTER / TIM KIEM VA LOC ═══ *@
        <div style="display:flex;gap:12px;margin-bottom:16px;align-items:center;">
            <div style="flex:1;display:flex;align-items:center;gap:8px;background:var(--admin-bg-elevated, #1E1E2E);
                        border:1px solid var(--admin-border-subtle, #333);border-radius:8px;padding:0 12px;">
                <i data-lucide="search" style="width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                <input type="text" @bind="_searchQuery" @bind:event="oninput"
                       placeholder="Tim theo ten, ma SKU hoac ma vach..."
                       style="flex:1;background:transparent;border:none;color:var(--admin-text-primary, #FFF);font-size:14px;
                              padding:10px 0;outline:none;font-family:inherit;" />
                @if (!string.IsNullOrEmpty(_searchQuery))
                {
                    <button style="background:none;border:none;color:var(--admin-text-tertiary);cursor:pointer;"
                            @onclick="() => _searchQuery = string.Empty">
                        <i data-lucide="x" style="width:14px;height:14px;"></i>
                    </button>
                }
            </div>

            @* EN: Stock status filter / VI: Loc trang thai ton kho *@
            <select @bind="_stockFilter"
                    style="background:var(--admin-bg-elevated, #1E1E2E);border:1px solid var(--admin-border-subtle, #333);
                           border-radius:8px;color:var(--admin-text-primary, #FFF);padding:10px 12px;font-size:13px;font-family:inherit;">
                <option value="all">Tat ca</option>
                <option value="in_stock">Con hang</option>
                <option value="low">Sap het</option>
                <option value="out">Het hang</option>
            </select>
        </div>

        @* ═══ STOCK TABLE / BANG TON KHO ═══ *@
        <div style="border:1px solid var(--admin-border-subtle, #333);border-radius:12px;overflow:hidden;">
            @* EN: Table header / VI: Header bang *@
            <div style="display:grid;grid-template-columns:2fr 1fr 1fr 100px 100px 100px 80px;
                        background:var(--admin-bg-elevated, #1E1E2E);padding:12px 16px;font-size:12px;font-weight:600;
                        color:var(--admin-text-tertiary);border-bottom:1px solid var(--admin-border-subtle, #333);">
                <span>San pham</span>
                <span>Ma SKU</span>
                <span>Ma vach</span>
                <span style="text-align:center;">Ton kho</span>
                <span style="text-align:center;">Da dat</span>
                <span style="text-align:center;">Muc toi thieu</span>
                <span style="text-align:center;">Trang thai</span>
            </div>

            @if (!FilteredItems.Any())
            {
                <div style="text-align:center;padding:40px;color:var(--admin-text-tertiary);font-size:14px;">
                    Khong tim thay san pham nao
                </div>
            }
            else
            {
                @foreach (var item in FilteredItems)
                {
                    var rowBg = GetRowBackground(item);
                    <div style="display:grid;grid-template-columns:2fr 1fr 1fr 100px 100px 100px 80px;
                                padding:12px 16px;font-size:13px;align-items:center;
                                border-bottom:1px solid var(--admin-border-subtle, #333);
                                background:@rowBg;transition:background .2s ease;"
                         @onmouseover="@(() => {})" @onmouseout="@(() => {})">
                        @* EN: Product name + category / VI: Ten san pham + danh muc *@
                        <div>
                            <div style="font-weight:600;color:var(--admin-text-primary, #FFF);">@item.ProductName</div>
                            <div style="font-size:11px;color:var(--admin-text-tertiary);margin-top:2px;">@(item.Category ?? "")</div>
                        </div>

                        <span style="color:var(--admin-text-secondary);font-family:monospace;">@(item.Sku ?? "-")</span>
                        <span style="color:var(--admin-text-secondary);font-family:monospace;">@(item.Barcode ?? "-")</span>

                        <span style="text-align:center;font-weight:700;color:@GetStockColor(item);">@item.Available</span>
                        <span style="text-align:center;color:var(--admin-text-tertiary);">@item.Reserved</span>

                        @* EN: Minimum level with edit button / VI: Muc toi thieu voi nut chinh sua *@
                        <div style="text-align:center;display:flex;align-items:center;justify-content:center;gap:4px;">
                            <span>@item.Minimum</span>
                            <button style="background:none;border:none;cursor:pointer;color:var(--admin-text-tertiary);padding:2px;"
                                    @onclick="() => OpenThresholdDialog(item)"
                                    title="Cai dat canh bao">
                                <i data-lucide="settings" style="width:12px;height:12px;"></i>
                            </button>
                        </div>

                        @* EN: Status badge / VI: Badge trang thai *@
                        <div style="text-align:center;">
                            <span style="font-size:11px;padding:3px 8px;border-radius:6px;font-weight:600;
                                         background:@GetStatusBg(item);color:@GetStatusColor(item);">
                                @GetStatusLabel(item)
                            </span>
                        </div>
                    </div>
                }
            }
        </div>

        @* EN: Result count / VI: So ket qua *@
        <div style="margin-top:12px;font-size:12px;color:var(--admin-text-tertiary);text-align:right;">
            Hien thi @FilteredItems.Count() / @_stockItems.Count san pham
        </div>
    }
</div>

@* ═══ THRESHOLD EDIT DIALOG / DIALOG CHINH SUA NGUONG ═══ *@
@if (_showThresholdDialog && _editingItem != null)
{
    <div style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1000;display:flex;align-items:center;justify-content:center;"
         @onclick="CloseThresholdDialog">
        <div style="background:var(--admin-bg-surface, #1A1A2E);border-radius:16px;padding:24px;width:400px;max-width:90vw;"
             @onclick:stopPropagation="true">
            <div style="font-size:16px;font-weight:700;margin-bottom:16px;color:var(--admin-text-primary, #FFF);">
                <i data-lucide="settings" style="width:18px;height:18px;margin-right:8px;color:var(--admin-orange-primary);display:inline;"></i>
                Cai dat canh bao ton kho
            </div>

            <div style="margin-bottom:12px;font-size:13px;color:var(--admin-text-secondary);">
                San pham: <strong>@_editingItem.ProductName</strong>
            </div>
            <div style="margin-bottom:12px;font-size:13px;color:var(--admin-text-secondary);">
                Ton kho hien tai: <strong>@_editingItem.Available</strong>
            </div>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">
                    Muc ton kho toi thieu
                </label>
                <input type="number" @bind="_thresholdValue" min="0"
                       style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle, #333);border-radius:8px;
                              font-size:14px;background:var(--admin-bg-elevated, #1E1E2E);color:var(--admin-text-primary, #FFF);" />
            </div>

            <div style="display:flex;gap:8px;justify-content:flex-end;">
                <button @onclick="CloseThresholdDialog"
                        style="padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle, #333);
                               background:transparent;color:var(--admin-text-secondary);font-size:13px;cursor:pointer;">
                    Huy
                </button>
                <button @onclick="SaveThreshold"
                        style="padding:8px 16px;border-radius:8px;border:none;background:var(--admin-orange-primary);
                               color:#FFF;font-size:13px;font-weight:600;cursor:pointer;">
                    Luu
                </button>
            </div>
        </div>
    </div>
}

@code {
    // EN: ShopId from route parameter / VI: ShopId tu route parameter
    [Parameter] public Guid ShopId { get; set; }

    private bool _isLoading = true;
    private string _searchQuery = "";
    private string _stockFilter = "all";

    // EN: Stock data / VI: Du lieu ton kho
    private List<StockItemViewModel> _stockItems = new();

    // EN: Summary counts / VI: So lieu tom tat
    private int _totalProducts;
    private int _inStockCount;
    private int _lowStockCount;
    private int _outOfStockCount;

    // EN: Threshold dialog / VI: Dialog nguong
    private bool _showThresholdDialog;
    private StockItemViewModel? _editingItem;
    private int _thresholdValue;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadDataAsync();
    }

    private async Task LoadDataAsync()
    {
        _isLoading = true;
        StateHasChanged();

        try
        {
            // EN: Load products and inventory in parallel / VI: Tai san pham va ton kho song song
            var productsTask = DataService.GetProductsAsync(ShopId);
            var inventoryTask = DataService.GetInventoryAsync(ShopId);

            await Task.WhenAll(productsTask, inventoryTask);

            var products = productsTask.Result;
            var inventory = inventoryTask.Result;

            // EN: Also try to load stock levels / VI: Cung thu tai muc ton kho
            List<PosDataService.StockLevelInfo> stockLevels = new();
            try
            {
                var productIds = products.Select(p => p.Id).ToList();
                if (productIds.Any())
                    stockLevels = await DataService.GetStockLevelsAsync(ShopId, productIds);
            }
            catch { /* Stock levels optional */ }

            var stockMap = stockLevels.ToDictionary(s => s.ProductId);
            var invMap = inventory.ToDictionary(i => i.ProductId);

            _stockItems = products.Select(p =>
            {
                var hasStock = stockMap.TryGetValue(p.Id, out var stock);
                var hasInv = invMap.TryGetValue(p.Id, out var inv);

                return new StockItemViewModel
                {
                    ProductId = p.Id,
                    ProductName = p.Name,
                    Sku = p.Sku,
                    Barcode = p.Sku, // EN: Use SKU as barcode fallback / VI: Dung SKU thay ma vach
                    Category = p.Category,
                    Available = hasStock ? stock!.Available : (hasInv ? inv!.Quantity : 0),
                    Reserved = hasStock ? stock!.Reserved : (hasInv ? inv!.ReservedQuantity : 0),
                    Minimum = hasStock ? stock!.Minimum : (hasInv ? inv!.ReorderLevel : 0),
                    IsLowStock = hasStock ? stock!.IsLowStock : (hasInv && inv!.Quantity <= inv.ReorderLevel),
                    InventoryId = hasInv ? inv!.Id : (Guid?)null
                };
            }).ToList();

            // EN: Calculate summary / VI: Tinh tom tat
            _totalProducts = _stockItems.Count;
            _outOfStockCount = _stockItems.Count(i => i.Available <= 0);
            _lowStockCount = _stockItems.Count(i => i.Available > 0 && i.IsLowStock);
            _inStockCount = _stockItems.Count(i => i.Available > 0 && !i.IsLowStock);
        }
        catch
        {
            Snackbar.Add("Khong the tai du lieu ton kho", Severity.Error);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private async Task RefreshData() => await LoadDataAsync();

    /// <summary>
    /// EN: Filtered items based on search query and stock filter.
    /// VI: San pham da loc theo truy van tim kiem va bo loc ton kho.
    /// </summary>
    private IEnumerable<StockItemViewModel> FilteredItems
    {
        get
        {
            var result = _stockItems.AsEnumerable();

            if (!string.IsNullOrWhiteSpace(_searchQuery))
            {
                var q = _searchQuery.Trim();
                result = result.Where(i =>
                    (i.ProductName?.Contains(q, StringComparison.OrdinalIgnoreCase) ?? false) ||
                    (i.Sku?.Contains(q, StringComparison.OrdinalIgnoreCase) ?? false) ||
                    (i.Barcode?.Contains(q, StringComparison.OrdinalIgnoreCase) ?? false));
            }

            result = _stockFilter switch
            {
                "in_stock" => result.Where(i => i.Available > 0 && !i.IsLowStock),
                "low" => result.Where(i => i.Available > 0 && i.IsLowStock),
                "out" => result.Where(i => i.Available <= 0),
                _ => result
            };

            return result;
        }
    }

    // EN: Row background color for low/out of stock / VI: Mau nen hang cho het/sap het hang
    private static string GetRowBackground(StockItemViewModel item) =>
        item.Available <= 0 ? "rgba(239,68,68,.06)" :
        item.IsLowStock ? "rgba(245,158,11,.04)" : "transparent";

    private static string GetStockColor(StockItemViewModel item) =>
        item.Available <= 0 ? "#EF4444" : item.IsLowStock ? "#F59E0B" : "#22C55E";

    private static string GetStatusBg(StockItemViewModel item) =>
        item.Available <= 0 ? "rgba(239,68,68,.15)" :
        item.IsLowStock ? "rgba(245,158,11,.15)" : "rgba(34,197,94,.15)";

    private static string GetStatusColor(StockItemViewModel item) =>
        item.Available <= 0 ? "#EF4444" : item.IsLowStock ? "#F59E0B" : "#22C55E";

    private static string GetStatusLabel(StockItemViewModel item) =>
        item.Available <= 0 ? "Het hang" : item.IsLowStock ? "Sap het" : "Du hang";

    // EN: Threshold dialog methods / VI: Cac phuong thuc dialog nguong
    private void OpenThresholdDialog(StockItemViewModel item)
    {
        _editingItem = item;
        _thresholdValue = item.Minimum;
        _showThresholdDialog = true;
    }

    private void CloseThresholdDialog()
    {
        _showThresholdDialog = false;
        _editingItem = null;
    }

    private async Task SaveThreshold()
    {
        if (_editingItem == null) return;

        try
        {
            if (_editingItem.InventoryId.HasValue)
            {
                var ok = await DataService.UpdateInventoryAsync(_editingItem.InventoryId.Value,
                    new PosDataService.UpdateInventoryRequest(_editingItem.Available, _thresholdValue));

                if (ok)
                {
                    _editingItem.Minimum = _thresholdValue;
                    _editingItem.IsLowStock = _editingItem.Available <= _thresholdValue;
                    // EN: Recalculate summaries / VI: Tinh lai tom tat
                    _outOfStockCount = _stockItems.Count(i => i.Available <= 0);
                    _lowStockCount = _stockItems.Count(i => i.Available > 0 && i.IsLowStock);
                    _inStockCount = _stockItems.Count(i => i.Available > 0 && !i.IsLowStock);
                    Snackbar.Add("Da cap nhat muc canh bao", Severity.Success);
                }
                else
                {
                    Snackbar.Add("Khong the cap nhat", Severity.Error);
                }
            }
            else
            {
                Snackbar.Add("San pham chua co trong ton kho", Severity.Warning);
            }
        }
        catch
        {
            Snackbar.Add("Loi khi cap nhat nguong", Severity.Error);
        }

        CloseThresholdDialog();
    }

    // EN: ViewModel for stock table row / VI: ViewModel cho hang trong bang ton kho
    private class StockItemViewModel
    {
        public Guid ProductId { get; set; }
        public string ProductName { get; set; } = "";
        public string? Sku { get; set; }
        public string? Barcode { get; set; }
        public string? Category { get; set; }
        public int Available { get; set; }
        public int Reserved { get; set; }
        public int Minimum { get; set; }
        public bool IsLowStock { get; set; }
        public Guid? InventoryId { get; set; }
    }
}
