@*
    EN: Retail POS Desktop — Barcode scanning, product grid with stock indicators, cart with quantity controls,
        stock level badges, returns/exchange access. Products and stock loaded from API.
    VI: POS Ban le Desktop — Quet ma vach, luoi san pham voi chi bao ton kho, gio hang voi dieu khien so luong,
        badge muc ton kho, truy cap tra/doi hang. San pham va ton kho tai tu API.
*@
@page "/pos/{ShopId:guid}/retail"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject ISnackbar Snackbar

@* ═══ PRODUCT PANEL ═══ *@
<div class="pos-product-panel">
    @* EN: Barcode input with auto-focus / VI: O nhap ma vach voi auto-focus *@
    <div style="padding:10px 16px;border-bottom:1px solid var(--pos-border-subtle);">
        <div style="display:flex;align-items:center;gap:8px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:0 12px;">
            <i data-lucide="scan-barcode" style="width:16px;height:16px;color:var(--pos-text-tertiary);"></i>
            <input @ref="_barcodeRef" type="text" @bind="_barcodeInput" @bind:event="oninput"
                   @onkeydown="OnBarcodeKeyDown"
                   placeholder="Quet ma vach hoac nhap SKU..."
                   style="flex:1;background:transparent;border:none;color:var(--pos-text-primary);font-size:13px;
                          padding:10px 0;outline:none;font-family:inherit;" />
            <button style="background:var(--pos-orange-primary);border:none;color:#fff;padding:6px 12px;border-radius:6px;
                           font-size:12px;font-weight:600;cursor:pointer;" @onclick="SearchBarcode">Tim</button>
        </div>
    </div>

    @* EN: Barcode lookup result alert / VI: Thong bao ket qua tra cuu ma vach *@
    @if (_barcodeNotFound)
    {
        <div style="margin:8px 16px;padding:10px 14px;background:rgba(245,158,11,.1);border:1px solid rgba(245,158,11,.25);
                    border-radius:8px;display:flex;align-items:center;gap:8px;">
            <i data-lucide="alert-triangle" style="width:16px;height:16px;color:var(--pos-warning);"></i>
            <span style="font-size:13px;color:var(--pos-warning);font-weight:600;">Khong tim thay san pham</span>
            <button style="margin-left:auto;background:none;border:none;color:var(--pos-text-tertiary);cursor:pointer;"
                    @onclick="() => _barcodeNotFound = false">
                <i data-lucide="x" style="width:14px;height:14px;"></i>
            </button>
        </div>
    }

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            <MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Warning" Class="mr-2" /> Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Khong the tai du lieu
        </div>
    }
    else
    {
        @* EN: Category tabs / VI: Tab danh muc *@
        <div class="pos-category-tabs">
            @foreach (var cat in _categories)
            {
                <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                        @onclick="() => _selectedCategory = cat">
                    @cat
                </button>
            }
        </div>

        @* EN: Product grid with stock indicators / VI: Luoi san pham voi chi bao ton kho *@
        <div class="pos-product-grid">
            @foreach (var product in FilteredProducts)
            {
                <div class="pos-product-card" @onclick="() => AddToCart(product)">
                    <div class="pos-product-card__image" style="display:flex;align-items:center;justify-content:center;position:relative;">
                        <i data-lucide="@product.Icon" style="width:32px;height:32px;color:var(--pos-text-tertiary);"></i>
                        @* EN: Stock badge / VI: Badge ton kho *@
                        @if (product.StockInfo != null)
                        {
                            <span style="position:absolute;top:4px;right:4px;font-size:9px;padding:2px 6px;border-radius:4px;font-weight:700;
                                         background:@(product.StockInfo.IsLowStock ? "rgba(239,68,68,.15)" : "rgba(34,197,94,.15)");
                                         color:@(product.StockInfo.IsLowStock ? "var(--pos-danger)" : "var(--pos-success)");">
                                @(product.StockInfo.Available <= 0 ? "Het" : product.StockInfo.IsLowStock ? $"Con {product.StockInfo.Available}" : $"{product.StockInfo.Available}")
                            </span>
                        }
                    </div>
                    <span class="pos-product-card__name">@product.Name</span>
                    <div style="display:flex;justify-content:space-between;align-items:center;width:100%;padding:0 4px;">
                        <span class="pos-product-card__price">@FormatPrice(product.Price)</span>
                        <span style="font-size:10px;color:var(--pos-text-tertiary);">@product.Sku</span>
                    </div>
                </div>
            }
        </div>
    }
</div>

@* ═══ CART PANEL ═══ *@
<div class="pos-cart-panel">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title">Gio hang</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">@_cartItems.Count san pham</span>
    </div>

    <div class="pos-cart-items">
        @foreach (var item in _cartItems)
        {
            <div class="pos-cart-item">
                <div class="pos-cart-item__info">
                    <span class="pos-cart-item__name">@item.Name</span>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span style="font-size:11px;color:var(--pos-text-tertiary);">@item.Sku</span>
                        @* EN: Stock indicator chip / VI: Chip chi bao ton kho *@
                        @if (item.StockAvailable.HasValue)
                        {
                            <span style="font-size:9px;padding:1px 5px;border-radius:3px;font-weight:600;
                                         background:@(item.StockAvailable.Value <= 0 ? "rgba(239,68,68,.15)" : item.Qty > item.StockAvailable.Value ? "rgba(245,158,11,.15)" : "rgba(34,197,94,.15)");
                                         color:@(item.StockAvailable.Value <= 0 ? "var(--pos-danger)" : item.Qty > item.StockAvailable.Value ? "var(--pos-warning)" : "var(--pos-success)");">
                                Ton: @item.StockAvailable
                            </span>
                        }
                    </div>
                    <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                </div>
                <div class="pos-cart-item__qty">
                    <button @onclick="() => ChangeQty(item, -1)">-</button>
                    <span style="font-size:14px;font-weight:600;min-width:20px;text-align:center;">@item.Qty</span>
                    <button @onclick="() => ChangeQty(item, 1)">+</button>
                </div>
            </div>
        }
    </div>

    <div class="pos-cart-footer">
        @* EN: Subtotals / VI: Tam tinh *@
        <div style="padding:0 12px 8px;font-size:12px;">
            <div style="display:flex;justify-content:space-between;color:var(--pos-text-tertiary);margin-bottom:4px;">
                <span>Tam tinh (@_cartItems.Sum(i => i.Qty) SP)</span>
                <span>@FormatPrice(CartSubtotal)</span>
            </div>
            @if (_discountAmount > 0)
            {
                <div style="display:flex;justify-content:space-between;color:var(--pos-success);margin-bottom:4px;">
                    <span>Giam gia</span>
                    <span>-@FormatPrice(_discountAmount)</span>
                </div>
            }
            <div style="display:flex;justify-content:space-between;color:var(--pos-text-tertiary);">
                <span>VAT (10%)</span>
                <span>@FormatPrice((CartSubtotal - _discountAmount) * 0.1m)</span>
            </div>
        </div>
        <div class="pos-cart-total">
            <span class="pos-cart-total__label">Tong cong</span>
            <span class="pos-cart-total__value">@FormatPrice(CartTotal)</span>
        </div>

        @* EN: Action buttons / VI: Nut hanh dong *@
        <div style="display:flex;gap:8px;padding:0 12px 8px;">
            <button style="flex:1;padding:10px;border-radius:8px;border:1px solid var(--pos-border-default);background:transparent;
                           color:var(--pos-text-secondary);font-size:12px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:4px;"
                    @onclick="ClearCart">
                <i data-lucide="trash-2" style="width:14px;height:14px;"></i> Xoa gio
            </button>
            <button style="flex:1;padding:10px;border-radius:8px;border:1px solid var(--pos-border-default);background:transparent;
                           color:var(--pos-text-secondary);font-size:12px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:4px;"
                    @onclick="@(() => NavigateTo("retail/return-exchange"))">
                <i data-lucide="rotate-ccw" style="width:14px;height:14px;"></i> Tra hang
            </button>
        </div>

        <button class="pos-btn-checkout" @onclick="Checkout" disabled="@(!_cartItems.Any())">
            <i data-lucide="credit-card" style="width:18px;height:18px;"></i>
            Thanh toan
        </button>
    </div>
</div>

@code {
    // EN: Loading state / VI: Trang thai tai
    private bool _isLoading = true;
    private bool _loadError;
    private bool _barcodeNotFound;
    private bool _isSearching;

    // EN: Categories / VI: Danh muc
    private string[] _categories = { "Tat ca" };
    private string _selectedCategory = "Tat ca";
    private string _barcodeInput = "";
    private ElementReference _barcodeRef;

    // EN: Discount / VI: Giam gia
    private decimal _discountAmount;

    // EN: Product list from API with stock info / VI: Danh sach san pham tu API voi thong tin ton kho
    private List<ProductWithStock> _products = new();

    // EN: Cart items / VI: Muc gio hang
    private readonly List<CartItem> _cartItems = new();
    private IEnumerable<ProductWithStock> FilteredProducts =>
        _selectedCategory == "Tat ca" ? _products : _products.Where(p => p.Category == _selectedCategory);
    private decimal CartSubtotal => _cartItems.Sum(i => i.Price * i.Qty);
    private decimal CartTotal => (CartSubtotal - _discountAmount) * 1.1m;

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

        try
        {
            // EN: Load products from catalog / VI: Tai san pham tu catalog
            var apiProducts = await DataService.GetProductsAsync(ShopId);

            _products = apiProducts.Select(p => new ProductWithStock(
                p.Id,
                p.Name,
                p.Sku ?? "",
                p.Price,
                p.Category ?? "Khac",
                GetCategoryIcon(p.Category ?? "Khac"),
                null
            )).ToList();

            var cats = _products.Select(p => p.Category).Distinct().ToList();
            _categories = new[] { "Tat ca" }.Concat(cats).ToArray();

            // EN: Load stock levels for all products / VI: Tai muc ton kho cho tat ca san pham
            await LoadStockLevelsAsync();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    /// <summary>
    /// EN: Load stock levels for all products in the grid.
    /// VI: Tai muc ton kho cho tat ca san pham trong luoi.
    /// </summary>
    private async Task LoadStockLevelsAsync()
    {
        try
        {
            var productIds = _products.Select(p => p.Id).ToList();
            if (!productIds.Any()) return;

            var stockLevels = await DataService.GetStockLevelsAsync(ShopId, productIds);
            var stockMap = stockLevels.ToDictionary(s => s.ProductId);

            _products = _products.Select(p =>
                stockMap.TryGetValue(p.Id, out var stock)
                    ? p with { StockInfo = stock }
                    : p
            ).ToList();
        }
        catch
        {
            // EN: Stock levels are optional; continue without them
            // VI: Muc ton kho la tuy chon; tiep tuc khong co
        }
    }

    /// <summary>
    /// EN: Handle Enter key in barcode input for quick scan.
    /// VI: Xu ly phim Enter trong o nhap ma vach de quet nhanh.
    /// </summary>
    private async Task OnBarcodeKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(_barcodeInput))
        {
            await SearchBarcode();
        }
    }

    /// <summary>
    /// EN: Search product by barcode/SKU — first check local list, then call API.
    /// VI: Tim san pham theo ma vach/SKU — kiem tra danh sach local truoc, sau do goi API.
    /// </summary>
    private async Task SearchBarcode()
    {
        if (string.IsNullOrWhiteSpace(_barcodeInput)) return;

        _barcodeNotFound = false;
        _isSearching = true;
        StateHasChanged();

        // EN: First try local match by SKU / VI: Thu khop local theo SKU truoc
        var found = _products.FirstOrDefault(p =>
            p.Sku.Equals(_barcodeInput, StringComparison.OrdinalIgnoreCase));

        if (found != null)
        {
            AddToCart(found);
            _barcodeInput = "";
            _isSearching = false;
            return;
        }

        // EN: Then try API barcode lookup / VI: Sau do thu tra cuu API theo ma vach
        try
        {
            var lookupResult = await DataService.LookupProductByBarcodeAsync(ShopId, _barcodeInput);
            if (lookupResult != null)
            {
                // EN: Check if product already in grid / VI: Kiem tra san pham da co trong luoi chua
                var existing = _products.FirstOrDefault(p => p.Id == lookupResult.Id);
                if (existing != null)
                {
                    AddToCart(existing);
                }
                else
                {
                    // EN: Add to grid and cart / VI: Them vao luoi va gio hang
                    var newProduct = new ProductWithStock(lookupResult.Id, lookupResult.Name,
                        lookupResult.Sku ?? lookupResult.Barcode ?? "", lookupResult.Price,
                        "Khac", "package", null);
                    _products.Add(newProduct);
                    AddToCart(newProduct);
                }
                _barcodeInput = "";
            }
            else
            {
                _barcodeNotFound = true;
                Snackbar.Add("Khong tim thay san pham voi ma vach nay", Severity.Warning);
            }
        }
        catch
        {
            _barcodeNotFound = true;
            Snackbar.Add("Loi khi tra cuu san pham", Severity.Error);
        }
        finally
        {
            _isSearching = false;
        }
    }

    private void AddToCart(ProductWithStock product)
    {
        // EN: Check stock availability / VI: Kiem tra ton kho
        if (product.StockInfo != null && product.StockInfo.Available <= 0)
        {
            Snackbar.Add($"{product.Name} da het hang", Severity.Warning);
            return;
        }

        var existing = _cartItems.FirstOrDefault(i => i.ProductId == product.Id);
        if (existing != null)
        {
            existing.Qty++;
            // EN: Warn if exceeding stock / VI: Canh bao neu vuot ton kho
            if (existing.StockAvailable.HasValue && existing.Qty > existing.StockAvailable.Value)
                Snackbar.Add($"{product.Name}: so luong vuot ton kho ({existing.StockAvailable})", Severity.Warning);
        }
        else
        {
            _cartItems.Add(new CartItem(product.Id, product.Name, product.Sku, product.Price,
                product.StockInfo?.Available));
        }
    }

    private void ChangeQty(CartItem item, int delta)
    {
        item.Qty += delta;
        if (item.Qty <= 0) _cartItems.Remove(item);
        else if (item.StockAvailable.HasValue && item.Qty > item.StockAvailable.Value)
            Snackbar.Add($"{item.Name}: so luong vuot ton kho ({item.StockAvailable})", Severity.Warning);
    }

    private void ClearCart()
    {
        _cartItems.Clear();
        _discountAmount = 0;
    }

    private void Checkout()
    {
        if (!_cartItems.Any()) return;
        NavigateTo("payment-method-select");
    }

    private static string GetCategoryIcon(string category) => category switch
    {
        "Thoi trang" => "shirt", "Phu kien" => "shopping-bag", "Dien tu" => "headphones",
        "Gia dung" => "cooking-pot", "My pham" => "sparkles", _ => "package"
    };

    // EN: Models / VI: Mo hinh du lieu
    private record ProductWithStock(Guid Id, string Name, string Sku, decimal Price, string Category, string Icon,
        PosDataService.StockLevelInfo? StockInfo);
    private class CartItem(Guid productId, string name, string sku, decimal price, int? stockAvailable)
    {
        public Guid ProductId { get; set; } = productId;
        public string Name { get; set; } = name;
        public string Sku { get; set; } = sku;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = 1;
        public int? StockAvailable { get; set; } = stockAvailable;
    }
}
