@*
    EN: Product Search — Search by name, SKU, barcode with filters. Add to cart from results.
    VI: Tìm kiếm sản phẩm — Tìm theo tên, SKU, mã vạch với bộ lọc. Thêm vào giỏ từ kết quả.
*@
@page "/pos/{ShopId:guid}/retail/product-search"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER ═══ *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:12px;">
        <button class="pos-category-tab" @onclick="@(() => NavigateTo("retail"))">
            <i data-lucide="arrow-left" style="width:14px;"></i> Quay lại
        </button>
        <span style="font-size:16px;font-weight:700;">Tìm kiếm sản phẩm</span>
    </div>

    @* ═══ SEARCH BAR / THANH TÌM KIẾM ═══ *@
    <div style="padding:12px 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 14px;">
            <i data-lucide="search" style="width:16px;height:16px;color:var(--pos-text-tertiary);"></i>
            <input type="text" @bind="_searchQuery" @bind:event="oninput"
                   placeholder="Tìm theo tên, SKU hoặc mã vạch..."
                   style="flex:1;background:transparent;border:none;color:var(--pos-text-primary);font-size:14px;
                          padding:12px 0;outline:none;font-family:inherit;" />
            @if (!string.IsNullOrEmpty(_searchQuery))
            {
                <button style="background:none;border:none;color:var(--pos-text-tertiary);cursor:pointer;"
                        @onclick="() => _searchQuery = string.Empty">
                    <i data-lucide="x" style="width:16px;height:16px;"></i>
                </button>
            }
        </div>
    </div>

    @* ═══ FILTERS / BỘ LỌC ═══ *@
    <div style="padding:10px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;gap:12px;align-items:center;">
        @* EN: Category filter / VI: Lọc danh mục *@
        <div class="pos-category-tabs" style="padding:0;flex:1;">
            @foreach (var cat in _categories)
            {
                <button class="pos-category-tab @(cat == _filterCategory ? "pos-category-tab--active" : "")"
                        style="font-size:12px;padding:6px 12px;" @onclick="() => _filterCategory = cat">@cat</button>
            }
        </div>

        @* EN: Price range / VI: Khoảng giá *@
        <select @bind="_priceRange"
                style="background:var(--pos-bg-interactive);border:1px solid var(--pos-border-default);border-radius:6px;
                       color:var(--pos-text-primary);padding:6px 10px;font-size:12px;font-family:inherit;">
            <option value="all">Tất cả giá</option>
            <option value="under200">Dưới 200K</option>
            <option value="200to500">200K - 500K</option>
            <option value="over500">Trên 500K</option>
        </select>
    </div>

    @* ═══ SEARCH RESULTS / KẾT QUẢ TÌM KIẾM ═══ *@
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    <div style="flex:1;overflow-y:auto;padding:12px 16px;">
        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:12px;">
            @FilteredResults.Count() kết quả @(!string.IsNullOrEmpty(_searchQuery) ? $"cho \"{_searchQuery}\"" : "")
        </div>

        @foreach (var product in FilteredResults)
        {
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px 16px;margin-bottom:8px;
                        display:flex;align-items:center;gap:14px;">
                @* EN: Product image placeholder / VI: Ảnh sản phẩm (placeholder) *@
                <div style="width:56px;height:56px;border-radius:10px;background:var(--pos-bg-interactive);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i data-lucide="@product.Icon" style="width:24px;height:24px;color:var(--pos-text-tertiary);"></i>
                </div>

                @* EN: Product info / VI: Thông tin sản phẩm *@
                <div style="flex:1;">
                    <div style="font-size:14px;font-weight:600;">@product.Name</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:2px;">@product.Sku · @product.Category</div>
                    <div style="display:flex;align-items:center;gap:12px;margin-top:4px;">
                        <span style="font-size:15px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(product.Price)</span>
                    </div>
                </div>

                @* EN: Add to cart / VI: Thêm vào giỏ *@
                <button style="padding:10px 18px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;
                               font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;display:flex;align-items:center;gap:6px;"
                        @onclick="() => AddToCart(product)">
                    <i data-lucide="plus" style="width:14px;height:14px;"></i> Thêm
                </button>
            </div>
        }
    </div>
    }

    @* ═══ CART SUMMARY BAR / THANH TÓM TẮT GIỎ ═══ *@
    @if (_cartItems.Any())
    {
        <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);background:var(--pos-bg-elevated);
                    display:flex;align-items:center;justify-content:space-between;">
            <div>
                <span style="font-size:13px;color:var(--pos-text-secondary);">Giỏ hàng: @_cartItems.Sum(i => i.Qty) sản phẩm</span>
                <span style="font-size:15px;font-weight:700;color:var(--pos-orange-primary);margin-left:12px;">
                    @FormatPrice(_cartItems.Sum(i => i.Price * i.Qty))
                </span>
            </div>
            <button style="padding:10px 20px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;
                           font-size:13px;font-weight:600;cursor:pointer;" @onclick="@(() => NavigateTo("retail"))">
                Xem giỏ hàng
            </button>
        </div>
    }
</div>

@code {
    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    private string _searchQuery = "";
    private string _filterCategory = "Tất cả";
    private string _priceRange = "all";
    private string[] _categories = { "Tất cả" };

    // EN: Product list from API / VI: Danh sách sản phẩm từ API
    private List<Product> _products = new();

    private readonly List<CartItem> _cartItems = new();

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

        try
        {
            var apiProducts = await DataService.GetProductsAsync(ShopId);

            _products = apiProducts.Select(p => new Product(
                p.Name,
                p.Sku ?? "",
                p.Price,
                p.Category ?? "Khác",
                GetCategoryIcon(p.Category ?? "Khác")
            )).ToList();

            var cats = _products.Select(p => p.Category).Distinct().ToList();
            _categories = new[] { "Tất cả" }.Concat(cats).ToArray();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private IEnumerable<Product> FilteredResults
    {
        get
        {
            var result = _products.AsEnumerable();
            if (!string.IsNullOrWhiteSpace(_searchQuery))
                result = result.Where(p => p.Name.Contains(_searchQuery, StringComparison.OrdinalIgnoreCase)
                    || p.Sku.Contains(_searchQuery, StringComparison.OrdinalIgnoreCase));
            if (_filterCategory != "Tất cả")
                result = result.Where(p => p.Category == _filterCategory);
            result = _priceRange switch
            {
                "under200" => result.Where(p => p.Price < 200_000),
                "200to500" => result.Where(p => p.Price >= 200_000 && p.Price <= 500_000),
                "over500" => result.Where(p => p.Price > 500_000),
                _ => result
            };
            return result;
        }
    }

    private void AddToCart(Product product)
    {
        var existing = _cartItems.FirstOrDefault(i => i.Sku == product.Sku);
        if (existing != null) existing.Qty++;
        else _cartItems.Add(new CartItem(product.Name, product.Sku, product.Price));
    }

    private static string GetCategoryIcon(string category) => category switch
    {
        "Thời trang" => "shirt", "Phụ kiện" => "shopping-bag", "Điện tử" => "headphones",
        "Gia dụng" => "cooking-pot", "Mỹ phẩm" => "sparkles", _ => "package"
    };

    // EN: Models / VI: Mô hình dữ liệu
    private record Product(string Name, string Sku, decimal Price, string Category, string Icon);
    private class CartItem(string name, string sku, decimal price)
    {
        public string Name { get; set; } = name;
        public string Sku { get; set; } = sku;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = 1;
    }
}
