@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService

<div>
    @if (!_inventory.Any() && _invSubTab == "levels")
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:rgba(59,130,246,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="warehouse" style="width:36px;height:36px;color:#3B82F6;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có tồn kho</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Tồn kho sẽ hiển thị khi có sản phẩm</p>
        </div>
    }
    else
    {
        <!-- Stats cards -->
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
            <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">@_inventory.Count(i => i.Quantity > 10)</span><span class="admin-stat-card__label">Còn hàng</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">@_inventory.Count(i => i.Quantity > 0 && i.Quantity <= 10)</span><span class="admin-stat-card__label">Sắp hết</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">@_inventory.Count(i => i.Quantity <= 0)</span><span class="admin-stat-card__label">Hết hàng</span></div></div>
        </div>

        <!-- EN: Action bar — add new inventory item button / VI: Thanh hành động — nút thêm nguyên liệu mới -->
        <div style="display:flex;justify-content:flex-end;margin-top:16px;">
            <button @onclick="@(() => { _showCreateForm = !_showCreateForm; })"
                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="plus" style="width:14px;height:14px;"></i> Thêm nguyên liệu
            </button>
        </div>

        @if (_showCreateForm)
        {
            <!-- EN: Create new inventory item form / VI: Form tạo mặt hàng tồn kho mới -->
            <div class="admin-panel" style="margin-top:12px;">
                <div class="admin-panel__header">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="package-plus" style="width:18px;height:18px;margin-right:8px;color:var(--admin-orange-primary);"></i>Thêm nguyên liệu / vật tư</h3>
                    <button @onclick="@(() => _showCreateForm = false)" style="background:transparent;border:none;cursor:pointer;color:var(--admin-text-tertiary);font-size:18px;">✕</button>
                </div>
                <div class="admin-panel__body" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;max-width:700px;">
                    <div style="grid-column:span 2;">
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Tên nguyên liệu *</label>
                        <input type="text" @bind="_createName" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="VD: Cà phê rang xay, Sữa tươi..." />
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Loại *</label>
                        <select @bind="_createItemTypeId" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                            <option value="1">Nguyên liệu</option>
                            <option value="2">Thành phẩm</option>
                            <option value="3">Vật tư tiêu hao</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Đơn vị *</label>
                        <select @bind="_createUnit" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                            <option value="g">g (gram)</option>
                            <option value="ml">ml (mililít)</option>
                            <option value="kg">kg (kilogram)</option>
                            <option value="L">L (lít)</option>
                            <option value="cái">cái</option>
                            <option value="gói">gói</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Giá nhập / đơn vị (VND) *</label>
                        <input type="number" @bind="_createCostPerUnit" min="0" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="0" />
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Số lượng ban đầu</label>
                        <input type="number" @bind="_createInitialQty" min="0" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="0" />
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Mức nhập lại</label>
                        <input type="number" @bind="_createReorderLevel" min="0" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="10" />
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Nhà cung cấp</label>
                        <input type="text" @bind="_createSupplier" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Tên nhà cung cấp..." />
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Hạn sử dụng</label>
                        <input type="date" @bind="_createExpiryDate" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" />
                    </div>
                    <div style="grid-column:span 2;">
                        <button @onclick="DoCreateInventoryItem" style="padding:10px 24px;background:var(--admin-orange-primary);color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                            <i data-lucide="plus" style="width:16px;height:16px;margin-right:6px;"></i>Tạo nguyên liệu
                        </button>
                    </div>
                </div>
            </div>
        }

        <!-- Sub-tabs -->
        <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;margin-top:16px;flex-wrap:wrap;">
            @foreach (var (label, val, icon) in new[] { ("Tồn kho", "levels", "package"), ("Nhập kho", "stock-in", "arrow-down-to-line"), ("Xuất kho", "stock-out", "arrow-up-from-line"), ("Điều chỉnh", "adjust", "settings-2"), ("Hao hụt", "wastage", "trash-2"), ("Kiểm kê", "stocktake", "clipboard-check"), ("Lịch sử", "transactions", "history"), ("Cảnh báo", "low-stock", "alert-triangle") })
            {
                <button @onclick="@(() => SwitchInvSubTab(val))"
                    style="padding:8px 14px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;border:none;display:flex;align-items:center;gap:6px;
                    @(_invSubTab == val ? "background:var(--admin-orange-primary);color:#FFF;box-shadow:0 1px 3px rgba(0,0,0,0.1);" : "background:transparent;color:var(--admin-text-tertiary);")">
                    <i data-lucide="@icon" style="width:14px;height:14px;"></i> @label
                </button>
            }
        </div>

        @if (_invFormMessage != null)
        {
            <div style="margin-top:12px;padding:12px 16px;border-radius:8px;font-size:13px;font-weight:500;background:@(_invFormSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");color:@(_invFormSuccess ? "#16A34A" : "#DC2626");">
                @_invFormMessage
            </div>
        }

        @switch (_invSubTab)
        {
            case "levels":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__body" style="padding:0;overflow-x:auto;">
                        <table class="admin-table" style="width:100%;"><thead><tr>
                            <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Sản phẩm</th>
                            <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Loại</th>
                            <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Số lượng</th>
                            <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Giá nhập</th>
                            <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mức nhập lại</th>
                            <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thao tác</th>
                        </tr></thead><tbody>
                            @foreach (var item in _inventory)
                            {
                                var qtyColor = item.Quantity <= 0 ? "#EF4444" : item.Quantity <= (item.ReorderLevel > 0 ? item.ReorderLevel : 10) ? "#F59E0B" : "#22C55E";
                                var bgColor = item.Quantity <= 0 ? "rgba(239,68,68,0.05)" : item.Quantity <= (item.ReorderLevel > 0 ? item.ReorderLevel : 10) ? "rgba(245,158,11,0.05)" : "transparent";
                                // EN: ItemType badge colors — RawMaterial=green, FinishedGood=blue, Consumable=gray
                                // VI: Màu badge loại — Nguyên liệu=xanh lá, Thành phẩm=xanh dương, Vật tư=xám
                                var (typeBadge, typeBg, typeColor) = item.ItemType switch
                                {
                                    "RawMaterial" => ("Nguyên liệu", "rgba(34,197,94,0.1)", "#16A34A"),
                                    "FinishedGood" => ("Thành phẩm", "rgba(59,130,246,0.1)", "#3B82F6"),
                                    "Consumable" => ("Vật tư", "rgba(107,114,128,0.1)", "#6B7280"),
                                    _ => ("—", "transparent", "var(--admin-text-tertiary)")
                                };
                                var unitLabel = item.Unit ?? "";
                                <tr style="border-top:1px solid var(--admin-border-subtle);background:@bgColor;">
                                    <td style="padding:12px 16px;font-weight:600;">@(item.ProductName ?? item.ProductId.ToString()[..8])</td>
                                    <td style="padding:12px 16px;text-align:center;">
                                        <span style="padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;background:@typeBg;color:@typeColor;">@typeBadge</span>
                                    </td>
                                    <td style="padding:12px 16px;text-align:right;font-weight:700;color:@qtyColor;">@item.Quantity @unitLabel</td>
                                    <td style="padding:12px 16px;text-align:right;font-size:13px;color:var(--admin-text-secondary);">@(item.CostPerUnit.HasValue ? item.CostPerUnit.Value.ToString("#,0") + "đ" : "—")</td>
                                    <td style="padding:12px 16px;text-align:right;font-size:13px;color:var(--admin-text-tertiary);">@item.ReorderLevel</td>
                                    <td style="padding:12px 16px;text-align:center;">
                                        <div style="display:flex;gap:4px;justify-content:center;">
                                            <button @onclick="@(() => { _invSubTab = "stock-in"; _invSelectedProductId = item.ProductId; _invAmount = 0; _invNotes = ""; StateHasChanged(); })"
                                                style="background:rgba(34,197,94,0.1);border:none;border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;color:#16A34A;cursor:pointer;">+Nhập</button>
                                            <button @onclick="@(() => { _invSubTab = "stock-out"; _invSelectedProductId = item.ProductId; _invAmount = 0; _invNotes = ""; StateHasChanged(); })"
                                                style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;color:#DC2626;cursor:pointer;">-Xuất</button>
                                            <button @onclick="@(() => DoDeleteInventoryItem(item.Id))"
                                                style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;color:#DC2626;cursor:pointer;"
                                                title="Xóa nguyên liệu">🗑</button>
                                        </div>
                                    </td>
                                </tr>
                            }
                        </tbody></table>
                    </div>
                </div>
                break;

            case "stock-in":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="arrow-down-to-line" style="width:18px;height:18px;margin-right:8px;color:#22C55E;"></i>Nhập kho</h3></div>
                    <div class="admin-panel__body" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;max-width:700px;">
                        <div style="grid-column:span 2;">
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Sản phẩm *</label>
                            <select @bind="_invSelectedProductId" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                                <option value="@Guid.Empty">-- Chọn sản phẩm --</option>
                                @foreach (var item in _inventory)
                                {
                                    <option value="@item.ProductId">@(item.ProductName ?? item.ProductId.ToString()[..8]) (Tồn: @item.Quantity @(item.Unit ?? ""))</option>
                                }
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Số lượng nhập *</label>
                            <input type="number" @bind="_invAmount" min="1" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Nhập số lượng..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Giá nhập / đơn vị (VND)</label>
                            <input type="number" @bind="_invStockInUnitCost" min="0" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Giá nhập lần này..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Nhà cung cấp</label>
                            <input type="text" @bind="_invStockInSupplier" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Tên nhà cung cấp..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Ghi chú</label>
                            <input type="text" @bind="_invNotes" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Lý do nhập kho..." />
                        </div>
                        <!-- EN: Invoice image upload placeholder / VI: Placeholder tải hóa đơn -->
                        <div style="grid-column:span 2;">
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Tải hóa đơn</label>
                            <div style="border:2px dashed var(--admin-border-subtle);border-radius:8px;padding:24px;text-align:center;cursor:pointer;background:var(--admin-bg-elevated);">
                                <i data-lucide="upload" style="width:28px;height:28px;color:var(--admin-text-tertiary);margin-bottom:8px;"></i>
                                <p style="margin:0;font-size:13px;color:var(--admin-text-tertiary);">Kéo thả hoặc click để tải ảnh hóa đơn</p>
                                <p style="margin:4px 0 0;font-size:11px;color:var(--admin-text-tertiary);opacity:0.6;">PNG, JPG — Tối đa 5MB (sắp ra mắt)</p>
                            </div>
                        </div>
                        <div style="grid-column:span 2;">
                            <button @onclick="DoStockIn" style="padding:10px 20px;background:#22C55E;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                                <i data-lucide="arrow-down-to-line" style="width:16px;height:16px;margin-right:6px;"></i>Nhập kho
                            </button>
                        </div>
                    </div>
                </div>
                break;

            case "stock-out":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="arrow-up-from-line" style="width:18px;height:18px;margin-right:8px;color:#EF4444;"></i>Xuất kho</h3></div>
                    <div class="admin-panel__body" style="display:grid;gap:16px;max-width:500px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Sản phẩm *</label>
                            <select @bind="_invSelectedProductId" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                                <option value="@Guid.Empty">-- Chọn sản phẩm --</option>
                                @foreach (var item in _inventory)
                                {
                                    <option value="@item.ProductId">@(item.ProductName ?? item.ProductId.ToString()[..8]) (Tồn: @item.Quantity)</option>
                                }
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Số lượng xuất *</label>
                            <input type="number" @bind="_invAmount" min="1" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Nhập số lượng..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Ghi chú</label>
                            <input type="text" @bind="_invNotes" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Lý do xuất kho..." />
                        </div>
                        <button @onclick="DoStockOut" style="padding:10px 20px;background:#EF4444;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                            <i data-lucide="arrow-up-from-line" style="width:16px;height:16px;margin-right:6px;"></i>Xuất kho
                        </button>
                    </div>
                </div>
                break;

            case "adjust":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="settings-2" style="width:18px;height:18px;margin-right:8px;color:#3B82F6;"></i>Điều chỉnh tồn kho</h3></div>
                    <div class="admin-panel__body" style="display:grid;gap:16px;max-width:500px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Sản phẩm *</label>
                            <select @bind="_invSelectedProductId" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                                <option value="@Guid.Empty">-- Chọn sản phẩm --</option>
                                @foreach (var item in _inventory)
                                {
                                    <option value="@item.ProductId">@(item.ProductName ?? item.ProductId.ToString()[..8]) (Tồn: @item.Quantity)</option>
                                }
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Số lượng mới *</label>
                            <input type="number" @bind="_invNewQty" min="0" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Đặt số lượng chính xác..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Lý do *</label>
                            <input type="text" @bind="_invNotes" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Lý do điều chỉnh..." />
                        </div>
                        <button @onclick="DoAdjustStock" style="padding:10px 20px;background:#3B82F6;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                            <i data-lucide="settings-2" style="width:16px;height:16px;margin-right:6px;"></i>Điều chỉnh
                        </button>
                    </div>
                </div>
                break;

            case "wastage":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="trash-2" style="width:18px;height:18px;margin-right:8px;color:#EF4444;"></i>Ghi nhận hao hụt</h3></div>
                    <div class="admin-panel__body" style="display:grid;gap:16px;max-width:500px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Nguyên liệu *</label>
                            <select @bind="_wastageSelectedItemId" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                                <option value="@Guid.Empty">-- Chọn nguyên liệu --</option>
                                @foreach (var item in _inventory)
                                {
                                    <option value="@item.Id">@(item.ProductName ?? item.ProductId.ToString()[..8]) (Tồn: @item.Quantity @(item.Unit ?? ""))</option>
                                }
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Số lượng hao hụt *</label>
                            <input type="number" @bind="_wastageAmount" min="1" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Nhập số lượng..." />
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Lý do *</label>
                            <select @bind="_wastageReason" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                                <option value="">-- Chọn lý do --</option>
                                <option value="Hết hạn">Hết hạn</option>
                                <option value="Hư hỏng">Hư hỏng</option>
                                <option value="Đổ/tràn">Đổ/tràn</option>
                                <option value="Khác">Khác</option>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:var(--admin-text-secondary);">Ghi chú</label>
                            <input type="text" @bind="_wastageNotes" style="width:100%;padding:10px 12px;border:1px solid var(--admin-border-subtle);border-radius:8px;font-size:14px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" placeholder="Chi tiết thêm..." />
                        </div>
                        <button @onclick="DoRecordWastage" style="padding:10px 20px;background:#EF4444;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                            <i data-lucide="trash-2" style="width:16px;height:16px;margin-right:6px;"></i>Ghi nhận hao hụt
                        </button>
                    </div>
                </div>
                break;

            case "stocktake":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="clipboard-check" style="width:18px;height:18px;margin-right:8px;color:#8B5CF6;"></i>Kiểm kê tồn kho</h3></div>
                    <div class="admin-panel__body" style="padding:0;overflow-x:auto;">
                        <table class="admin-table" style="width:100%;"><thead><tr>
                            <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Nguyên liệu</th>
                            <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tồn hệ thống</th>
                            <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Đếm thực tế</th>
                        </tr></thead><tbody>
                            @foreach (var item in _inventory)
                            {
                                var itemId = item.Id;
                                <tr style="border-top:1px solid var(--admin-border-subtle);">
                                    <td style="padding:12px 16px;font-weight:600;">@(item.ProductName ?? item.ProductId.ToString()[..8]) <span style="font-size:11px;color:var(--admin-text-tertiary);">@(item.Unit ?? "")</span></td>
                                    <td style="padding:12px 16px;text-align:right;font-weight:700;color:var(--admin-text-secondary);">@item.Quantity</td>
                                    <td style="padding:12px 16px;text-align:right;">
                                        <input type="number" min="0" value="@(GetStocktakeCount(itemId))"
                                            @onchange="@(e => SetStocktakeCount(itemId, int.TryParse(e.Value?.ToString(), out var v) ? v : 0))"
                                            style="width:100px;padding:6px 10px;border:1px solid var(--admin-border-subtle);border-radius:6px;font-size:14px;text-align:right;background:var(--admin-bg-elevated);color:var(--admin-text-primary);" />
                                    </td>
                                </tr>
                            }
                        </tbody></table>
                        <div style="padding:16px;display:flex;gap:12px;align-items:center;">
                            <button @onclick="DoStocktake" style="padding:10px 20px;background:#8B5CF6;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                                <i data-lucide="clipboard-check" style="width:16px;height:16px;margin-right:6px;"></i>Xác nhận kiểm kê
                            </button>
                        </div>
                    </div>
                </div>
                @if (_stocktakeResult != null)
                {
                    <div class="admin-panel" style="margin-top:16px;">
                        <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="bar-chart-3" style="width:18px;height:18px;margin-right:8px;color:#F59E0B;"></i>Kết quả kiểm kê (@_stocktakeResult.TotalItemsCounted mặt hàng)</h3></div>
                        <div class="admin-panel__body" style="padding:0;">
                            @if (_stocktakeResult.Discrepancies.Any())
                            {
                                <table class="admin-table" style="width:100%;"><thead><tr>
                                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Nguyên liệu</th>
                                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Hệ thống</th>
                                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thực tế</th>
                                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Chênh lệch</th>
                                </tr></thead><tbody>
                                    @foreach (var d in _stocktakeResult.Discrepancies)
                                    {
                                        var diffColor = d.Difference > 0 ? "#22C55E" : "#EF4444";
                                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                                            <td style="padding:12px 16px;font-weight:600;">@(d.ItemName ?? d.InventoryItemId.ToString()[..8])</td>
                                            <td style="padding:12px 16px;text-align:right;color:var(--admin-text-secondary);">@d.ExpectedQuantity</td>
                                            <td style="padding:12px 16px;text-align:right;font-weight:700;">@d.CountedQuantity</td>
                                            <td style="padding:12px 16px;text-align:right;font-weight:700;color:@diffColor;">@(d.Difference > 0 ? "+" : "")@d.Difference</td>
                                        </tr>
                                    }
                                </tbody></table>
                            }
                            else
                            {
                                <div style="text-align:center;padding:32px;color:var(--admin-text-tertiary);font-size:14px;">
                                    <i data-lucide="check-circle" style="width:32px;height:32px;color:#22C55E;margin-bottom:8px;"></i><br/>
                                    Không có chênh lệch. Tồn kho chính xác!
                                </div>
                            }
                        </div>
                    </div>
                }
                break;

            case "transactions":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header"><h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="history" style="width:18px;height:18px;margin-right:8px;color:#8B5CF6;"></i>Lịch sử giao dịch kho</h3></div>
                    <div class="admin-panel__body" style="padding:0;">
                        @if (_invTxns.Any())
                        {
                            <table class="admin-table" style="width:100%;"><thead><tr>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thời gian</th>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Loại</th>
                                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Số lượng</th>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Lý do</th>
                            </tr></thead><tbody>
                                @foreach (var tx in _invTxns.OrderByDescending(t => t.CreatedAt).Take(50))
                                {
                                    var txColor = tx.Quantity > 0 ? "#22C55E" : tx.Quantity < 0 ? "#EF4444" : "#6B7280";
                                    var txLabel = tx.TransactionType switch { "StockIn" or "In" => "Nhập kho", "StockOut" or "Out" => "Xuất kho", "Adjustment" => "Điều chỉnh", "OrderDeduction" => "Đơn hàng", "Reserve" => "Đặt trước", "Release" => "Giải phóng", "Wastage" => "Hao hụt", _ => tx.TransactionType ?? "N/A" };
                                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-secondary);">@tx.CreatedAt.ToLocalTime().ToString("dd/MM HH:mm")</td>
                                        <td style="padding:12px 16px;">
                                            <span style="padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;background:@(txColor)1a;color:@txColor;">@txLabel</span>
                                        </td>
                                        <td style="padding:12px 16px;text-align:right;font-weight:700;color:@txColor;">@(tx.Quantity > 0 ? "+" : "")@(tx.Quantity)</td>
                                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@(tx.Notes ?? "—")</td>
                                    </tr>
                                }
                            </tbody></table>
                        }
                        else
                        {
                            <div style="text-align:center;padding:32px;color:var(--admin-text-tertiary);font-size:14px;">Chưa có giao dịch kho nào.</div>
                        }
                    </div>
                </div>
                break;

            case "low-stock":
                <div class="admin-panel" style="margin-top:16px;">
                    <div class="admin-panel__header">
                        <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="alert-triangle" style="width:18px;height:18px;margin-right:8px;color:#F59E0B;"></i>Cảnh báo tồn kho thấp</h3>
                        <button @onclick="LoadLowStock" style="padding:6px 14px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;color:var(--admin-text-secondary);">
                            <i data-lucide="refresh-cw" style="width:12px;height:12px;margin-right:4px;"></i>Làm mới
                        </button>
                    </div>
                    <div class="admin-panel__body" style="padding:0;">
                        @if (_lowStockItems.Any())
                        {
                            <table class="admin-table" style="width:100%;"><thead><tr>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Sản phẩm</th>
                                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tồn kho</th>
                                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngưỡng</th>
                                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Hành động</th>
                            </tr></thead><tbody>
                                @foreach (var item in _lowStockItems)
                                {
                                    <tr style="border-top:1px solid var(--admin-border-subtle);background:rgba(245,158,11,0.03);">
                                        <td style="padding:12px 16px;font-weight:600;">@(item.ProductName ?? item.ProductId.ToString()[..8])</td>
                                        <td style="padding:12px 16px;text-align:right;font-weight:700;color:@(item.Quantity <= 0 ? "#EF4444" : "#F59E0B");">@item.Quantity</td>
                                        <td style="padding:12px 16px;text-align:right;font-size:13px;color:var(--admin-text-tertiary);">@item.LowStockThreshold</td>
                                        <td style="padding:12px 16px;text-align:center;">
                                            <button @onclick="@(() => { _invSubTab = "stock-in"; _invSelectedProductId = item.ProductId; _invAmount = item.LowStockThreshold * 2; _invNotes = "Bổ sung hàng tồn kho thấp"; StateHasChanged(); })"
                                                style="background:rgba(34,197,94,0.1);border:none;border-radius:6px;padding:4px 12px;font-size:11px;font-weight:600;color:#16A34A;cursor:pointer;">
                                                <i data-lucide="arrow-down-to-line" style="width:12px;height:12px;margin-right:4px;"></i>Nhập kho nhanh
                                            </button>
                                        </td>
                                    </tr>
                                }
                            </tbody></table>
                        }
                        else
                        {
                            <div style="text-align:center;padding:32px;color:var(--admin-text-tertiary);font-size:14px;">
                                <i data-lucide="check-circle" style="width:32px;height:32px;color:#22C55E;margin-bottom:8px;"></i><br/>
                                Tất cả sản phẩm đều đủ hàng!
                            </div>
                        }
                    </div>
                </div>
                break;
        }
    }
</div>

@code {
    [Parameter] public Guid ShopId { get; set; }

    private Guid? _shopGuid => ShopId != Guid.Empty ? ShopId : null;

    private List<PosDataService.InventoryItemInfo> _inventory = new();
    private List<PosDataService.InventoryTxnInfo> _invTxns = new();
    private string _invSubTab = "levels";
    private Guid _invSelectedProductId;
    private int _invAmount;
    private int _invNewQty;
    private string _invNotes = "";
    private string? _invFormMessage;
    private bool _invFormSuccess;
    private List<PosDataService.LowStockItemInfo> _lowStockItems = new();

    // EN: Create inventory item form state / VI: State form tạo nguyên liệu
    private bool _showCreateForm;
    private string _createName = "";
    private int _createItemTypeId = 1;
    private string _createUnit = "g";
    private decimal _createCostPerUnit;
    private int _createInitialQty;
    private int _createReorderLevel = 10;
    private string _createSupplier = "";
    private DateTime? _createExpiryDate;

    // EN: Stock-in extra fields / VI: Trường bổ sung cho nhập kho
    private decimal? _invStockInUnitCost;
    private string _invStockInSupplier = "";

    // EN: Wastage form state / VI: State form hao hụt
    private Guid _wastageSelectedItemId;
    private int _wastageAmount;
    private string _wastageReason = "";
    private string _wastageNotes = "";

    // EN: Stocktake state / VI: State kiểm kê
    private Dictionary<Guid, int> _stocktakeCounts = new();
    private PosDataService.StocktakeResult? _stocktakeResult;

    protected override async Task OnInitializedAsync()
    {
        _inventory = await DataService.GetInventoryAsync(_shopGuid);
        _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid);
    }

    private async Task SwitchInvSubTab(string tab)
    {
        _invSubTab = tab;
        _invFormMessage = null;
        if (tab == "low-stock") await LoadLowStock();
        StateHasChanged();
    }

    private async Task LoadLowStock()
    {
        _lowStockItems = await DataService.GetLowStockAsync(_shopGuid);
        StateHasChanged();
    }

    private async Task DoStockIn()
    {
        _invFormMessage = null;
        if (_invSelectedProductId == Guid.Empty || _invAmount <= 0) { _invFormMessage = "Vui lòng chọn sản phẩm và nhập số lượng > 0."; _invFormSuccess = false; return; }
        var supplier = string.IsNullOrWhiteSpace(_invStockInSupplier) ? null : _invStockInSupplier;
        var ok = await DataService.StockInAsync(new PosDataService.StockInRequest(
            _invSelectedProductId, ShopId, _invAmount,
            string.IsNullOrWhiteSpace(_invNotes) ? null : _invNotes,
            null, _invStockInUnitCost, supplier));
        _invFormMessage = ok ? $"Đã nhập kho thành công +{_invAmount}!" : "Lỗi khi nhập kho.";
        _invFormSuccess = ok;
        if (ok) { _invAmount = 0; _invNotes = ""; _invStockInUnitCost = null; _invStockInSupplier = ""; _inventory = await DataService.GetInventoryAsync(_shopGuid); _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid); }
    }

    private async Task DoStockOut()
    {
        _invFormMessage = null;
        if (_invSelectedProductId == Guid.Empty || _invAmount <= 0) { _invFormMessage = "Vui lòng chọn sản phẩm và nhập số lượng > 0."; _invFormSuccess = false; return; }
        var ok = await DataService.StockOutAsync(new PosDataService.StockOutRequest(_invSelectedProductId, ShopId, _invAmount, string.IsNullOrWhiteSpace(_invNotes) ? null : _invNotes));
        _invFormMessage = ok ? $"Đã xuất kho thành công -{_invAmount}!" : "Lỗi khi xuất kho. Kiểm tra số lượng tồn.";
        _invFormSuccess = ok;
        if (ok) { _invAmount = 0; _invNotes = ""; _inventory = await DataService.GetInventoryAsync(_shopGuid); _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid); }
    }

    private async Task DoAdjustStock()
    {
        _invFormMessage = null;
        if (_invSelectedProductId == Guid.Empty || string.IsNullOrWhiteSpace(_invNotes)) { _invFormMessage = "Vui lòng chọn sản phẩm và nhập lý do điều chỉnh."; _invFormSuccess = false; return; }
        var ok = await DataService.AdjustStockAsync(new PosDataService.AdjustStockRequest(_invSelectedProductId, ShopId, _invNewQty, _invNotes));
        _invFormMessage = ok ? $"Đã điều chỉnh tồn kho = {_invNewQty}!" : "Lỗi khi điều chỉnh.";
        _invFormSuccess = ok;
        if (ok) { _invNewQty = 0; _invNotes = ""; _inventory = await DataService.GetInventoryAsync(_shopGuid); _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid); }
    }

    private async Task DoRecordWastage()
    {
        _invFormMessage = null;
        if (_wastageSelectedItemId == Guid.Empty || _wastageAmount <= 0 || string.IsNullOrWhiteSpace(_wastageReason))
        {
            _invFormMessage = "Vui lòng chọn nguyên liệu, nhập số lượng > 0 và chọn lý do."; _invFormSuccess = false; return;
        }
        var ok = await DataService.RecordWastageAsync(new PosDataService.RecordWastageRequest(
            _wastageSelectedItemId, _wastageAmount, _wastageReason,
            string.IsNullOrWhiteSpace(_wastageNotes) ? null : _wastageNotes));
        _invFormMessage = ok ? $"Đã ghi nhận hao hụt -{_wastageAmount}!" : "Lỗi khi ghi nhận hao hụt.";
        _invFormSuccess = ok;
        if (ok) { _wastageAmount = 0; _wastageReason = ""; _wastageNotes = ""; _wastageSelectedItemId = Guid.Empty; _inventory = await DataService.GetInventoryAsync(_shopGuid); _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid); }
    }

    private int GetStocktakeCount(Guid itemId) => _stocktakeCounts.TryGetValue(itemId, out var v) ? v : 0;

    private void SetStocktakeCount(Guid itemId, int value) => _stocktakeCounts[itemId] = value;

    private async Task DoStocktake()
    {
        _invFormMessage = null;
        _stocktakeResult = null;
        var items = _inventory
            .Where(i => _stocktakeCounts.ContainsKey(i.Id))
            .Select(i => new PosDataService.StocktakeItemRequest(i.Id, _stocktakeCounts[i.Id]))
            .ToList();
        if (!items.Any()) { _invFormMessage = "Vui lòng nhập số lượng đếm cho ít nhất 1 mặt hàng."; _invFormSuccess = false; return; }
        var result = await DataService.StocktakeAsync(new PosDataService.StocktakeRequest(ShopId, items));
        if (result != null)
        {
            _stocktakeResult = result;
            _invFormMessage = $"Kiểm kê hoàn thành: {result.TotalItemsCounted} mặt hàng, {result.Discrepancies.Count} chênh lệch.";
            _invFormSuccess = true;
            _stocktakeCounts.Clear();
            _inventory = await DataService.GetInventoryAsync(_shopGuid);
            _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid);
        }
        else { _invFormMessage = "Lỗi khi thực hiện kiểm kê."; _invFormSuccess = false; }
    }

    private async Task DoDeleteInventoryItem(Guid itemId)
    {
        var item = _inventory.FirstOrDefault(i => i.Id == itemId);
        var name = item?.ProductName ?? "nguyên liệu";
        // Simple confirmation by checking quantity
        if (item != null && item.Quantity > 0)
        {
            _invFormMessage = $"⚠️ Không thể xóa '{name}' vì còn {item.Quantity} {item.Unit} trong kho. Hãy xuất hết trước.";
            _invFormSuccess = false;
            StateHasChanged();
            return;
        }
        var ok = await DataService.DeleteInventoryItemAsync(itemId);
        if (ok)
        {
            _invFormMessage = $"✅ Đã xóa '{name}' khỏi tồn kho!";
            _invFormSuccess = true;
            _inventory = await DataService.GetInventoryAsync(_shopGuid);
        }
        else
        {
            _invFormMessage = $"❌ Không thể xóa '{name}'.";
            _invFormSuccess = false;
        }
        StateHasChanged();
    }

    // EN: Create a new inventory item (raw material / supply) / VI: Tạo nguyên liệu / vật tư mới
    private async Task DoCreateInventoryItem()
    {
        _invFormMessage = null;
        if (string.IsNullOrWhiteSpace(_createName))
        {
            _invFormMessage = "Vui lòng nhập tên nguyên liệu."; _invFormSuccess = false; return;
        }
        var req = new PosDataService.CreateInventoryItemRequest(
            ShopId, _createName.Trim(), _createItemTypeId, _createUnit,
            _createCostPerUnit, _createInitialQty, _createReorderLevel,
            string.IsNullOrWhiteSpace(_createSupplier) ? null : _createSupplier.Trim(),
            _createExpiryDate);
        var ok = await DataService.CreateInventoryItemAsync(req);
        _invFormMessage = ok ? $"Đã tạo nguyên liệu \"{_createName}\" thành công!" : "Lỗi khi tạo nguyên liệu.";
        _invFormSuccess = ok;
        if (ok)
        {
            _createName = ""; _createCostPerUnit = 0; _createInitialQty = 0; _createReorderLevel = 10;
            _createSupplier = ""; _createExpiryDate = null; _showCreateForm = false;
            _inventory = await DataService.GetInventoryAsync(_shopGuid);
            _invTxns = await DataService.GetInventoryTransactionsAsync(_shopGuid);
        }
    }
}
