@* EN: Recipe management component — link ingredients to inventory items for COGS calculation.
   VI: Component quản lý công thức — liên kết nguyên liệu với mặt hàng tồn kho để tính giá vốn. *@
@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <h3 style="margin:0;font-size:16px;font-weight:700;">@_recipes.Count công thức</h3>
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _showRecipeForm = !_showRecipeForm; _editingRecipeId = null; _selectedProductId = Guid.Empty; _newRecipeName = ""; _newRecipeInstructions = ""; _newRecipePrepTime = 5; _recipeIngredients = new(); _recipeFormMessage = null; }'>
        <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm công thức
    </button>
</div>
@if (_showRecipeForm)
{
    <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(255,92,0,0.3);">
        <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingRecipeId.HasValue ? "Chỉnh sửa công thức" : "Thêm công thức mới")</h3></div>
        <div class="admin-panel__body">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên công thức *</label><input type="text" @bind="_newRecipeName" placeholder="VD: Cà phê sữa đá" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Thời gian chuẩn bị (phút)</label><input type="number" @bind="_newRecipePrepTime" min="1" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div style="grid-column:span 2;">
                    <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Sản phẩm liên kết *</label>
                    <select @bind="_selectedProductId" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                        <option value="@Guid.Empty">-- Chọn sản phẩm từ Menu --</option>
                        @foreach (var product in _products)
                        {
                            <option value="@product.Id">@product.Name (@(product.Price.ToString("N0"))đ)</option>
                        }
                    </select>
                </div>
                <div style="grid-column:span 2;"><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Hướng dẫn</label><textarea @bind="_newRecipeInstructions" rows="2" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);resize:vertical;"></textarea></div>
            </div>
            <div style="margin-bottom:12px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;"><span style="font-size:13px;font-weight:600;">Nguyên liệu / Ingredients</span><button @onclick="() => _recipeIngredients.Add(new IngredientRow())" style="padding:4px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-primary);font-size:12px;cursor:pointer;">+ Thêm</button></div>
                @for (var idx = 0; idx < _recipeIngredients.Count; idx++)
                {
                    var i = idx;
                    <div style="display:grid;grid-template-columns:2fr 2fr 1fr 1fr 1fr auto;gap:8px;margin-bottom:6px;">
                        @* EN: Inventory item dropdown — select from all inventory items / VI: Dropdown chọn từ tất cả mặt hàng tồn kho *@
                        <select value="@(_recipeIngredients[i].InventoryItemId?.ToString() ?? "")" @onchange="@(e => OnInventoryItemSelected(i, e.Value?.ToString()))" style="padding:6px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;">
                            <option value="">-- Chọn kho / Select inventory --</option>
                            @foreach (var item in _inventoryItems)
                            {
                                <option value="@item.Id">@(item.ProductName ?? item.Id.ToString()[..8]) (@item.Unit - @(item.CostPerUnit?.ToString("N0") ?? "0")d)</option>
                            }
                        </select>
                        <input value="@_recipeIngredients[i].Name" @onchange="@(e => { _recipeIngredients[i].Name = e.Value?.ToString() ?? ""; })" placeholder="Tên nguyên liệu" style="padding:6px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;" />
                        <input value="@_recipeIngredients[i].Quantity" @onchange="@(e => { _recipeIngredients[i].Quantity = decimal.TryParse(e.Value?.ToString(), out var v) ? v : 0; })" type="number" step="0.01" placeholder="Qty" style="padding:6px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;" />
                        <input value="@_recipeIngredients[i].Unit" @onchange="@(e => { _recipeIngredients[i].Unit = e.Value?.ToString() ?? ""; })" placeholder="Đơn vị" style="padding:6px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;" />
                        <input value="@_recipeIngredients[i].Cost" @onchange="@(e => { _recipeIngredients[i].Cost = decimal.TryParse(e.Value?.ToString(), out var v) ? v : 0; })" type="number" placeholder="Chi phí" style="padding:6px 10px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;" />
                        <button @onclick="() => _recipeIngredients.RemoveAt(i)" style="padding:6px;border-radius:6px;border:none;background:rgba(239,68,68,0.1);color:#EF4444;cursor:pointer;">X</button>
                    </div>
                    @if (_recipeIngredients[i].InventoryItemId != null)
                    {
                        <div style="font-size:11px;color:var(--admin-text-tertiary);margin-bottom:6px;margin-left:4px;">
                            Qty/serving: <input value="@_recipeIngredients[i].QuantityPerServing" @onchange="@(e => { _recipeIngredients[i].QuantityPerServing = decimal.TryParse(e.Value?.ToString(), out var v) ? v : 0; })" type="number" step="0.01" placeholder="Qty per serving" style="width:80px;padding:3px 6px;border-radius:4px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:11px;" />
                        </div>
                    }
                }
            </div>
            <div style="display:flex;gap:8px;">
                <button class="admin-btn-primary" @onclick="SaveRecipe" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>Lưu</button>
                <button @onclick='() => _showRecipeForm = false' style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
            </div>
            @if (_recipeFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_recipeFormSuccess ? "#22C55E" : "#EF4444");">@_recipeFormMessage</div> }
        </div>
    </div>
}
@if (!_recipes.Any())
{
    @RenderEmpty("flask-conical", "#FF5C00", "Chưa có công thức", "Thêm công thức và nguyên liệu pha chế")
}
else
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;">
        @foreach (var recipe in _recipes)
        {
            var isExpanded = _expandedRecipeId == recipe.Id;
            <div class="admin-panel" style="cursor:pointer;" @onclick='() => { _expandedRecipeId = isExpanded ? null : recipe.Id; StateHasChanged(); }'>
                <div class="admin-panel__body" style="padding:16px;">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px;">
                        <div style="font-weight:700;font-size:14px;">@recipe.Name</div>
                        <div style="display:flex;gap:4px;" @onclick:stopPropagation>
                            <button @onclick='() => StartEditRecipe(recipe)' style="background:rgba(255,92,0,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#FF5C00;width:12px;height:12px;"></i></button>
                            <button @onclick='() => DeleteRecipeItem(recipe.Id)' style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:12px;height:12px;"></i></button>
                        </div>
                    </div>
                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:4px;"><i data-lucide="clock" style="width:12px;height:12px;vertical-align:middle;"></i> @recipe.PrepTimeMinutes phút chuẩn bị</div>
                    @{ var linkedProduct = _products.FirstOrDefault(p => p.Id == recipe.ProductId); }
                    @if (linkedProduct != null)
                    {
                        <div style="font-size:11px;color:#FF5C00;margin-bottom:4px;"><i data-lucide="link" style="width:10px;height:10px;vertical-align:middle;"></i> @linkedProduct.Name (@(linkedProduct.Price.ToString("N0"))đ)</div>
                    }
                    @if (recipe.Ingredients != null && recipe.Ingredients.Any())
                    {
                        <div style="margin-top:8px;font-size:12px;">
                            <div style="font-weight:600;color:var(--admin-text-secondary);margin-bottom:4px;">Nguyên liệu:</div>
                            @foreach (var ing in recipe.Ingredients)
                            {
                                <div style="display:flex;justify-content:space-between;padding:2px 0;color:var(--admin-text-tertiary);">
                                    <span>@ing.IngredientName</span>
                                    <span>@(ing.Quantity % 1 == 0 ? ((int)ing.Quantity).ToString() : ing.Quantity.ToString("0.##")) @ing.Unit</span>
                                </div>
                            }
                        </div>
                    }
                    @if (isExpanded && !string.IsNullOrEmpty(recipe.Instructions))
                    {
                        <div style="font-size:12px;color:var(--admin-text-secondary);margin-top:8px;padding:8px;border-radius:6px;background:rgba(255,92,0,0.05);">@recipe.Instructions</div>
                    }
                </div>
            </div>
        }
    </div>
}

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

    // EN: Mutable class for ingredient row editing / VI: Class có thể chỉnh sửa cho hàng nguyên liệu
    private class IngredientRow
    {
        public string Name { get; set; } = "";
        public string Unit { get; set; } = "";
        public decimal Quantity { get; set; }
        public decimal Cost { get; set; }
        public Guid? InventoryItemId { get; set; }
        public decimal QuantityPerServing { get; set; }
    }

    // EN: Recipes state / VI: Trạng thái công thức
    private List<PosDataService.RecipeInfo> _recipes = new();
    private List<PosDataService.InventoryItemInfo> _inventoryItems = new();
    private List<PosDataService.ProductInfo> _products = new();
    private bool _showRecipeForm;
    private Guid? _editingRecipeId;
    private Guid _selectedProductId = Guid.Empty;
    private string _newRecipeName = "";
    private string _newRecipeInstructions = "";
    private int _newRecipePrepTime = 5;
    private List<IngredientRow> _recipeIngredients = new();
    private Guid? _expandedRecipeId;
    private string? _recipeFormMessage;
    private bool _recipeFormSuccess;
    private string? _errorMessage;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
        {
            // EN: Load recipes, inventory items, and products in parallel.
            // VI: Tải công thức, mặt hàng tồn kho và sản phẩm song song.
            var recipesTask = DataService.GetRecipesAsync(ShopId);
            var inventoryTask = DataService.GetInventoryAsync(ShopId);
            var productsTask = DataService.GetProductsAsync(ShopId);
            await Task.WhenAll(recipesTask, inventoryTask, productsTask);
            _recipes = recipesTask.Result;
            _inventoryItems = inventoryTask.Result;
            _products = productsTask.Result;
        }
    }

    // EN: When user selects an inventory item, auto-fill name, unit, cost.
    // VI: Khi người dùng chọn mặt hàng tồn kho, tự động điền tên, đơn vị, chi phí.
    private void OnInventoryItemSelected(int index, string? value)
    {
        if (string.IsNullOrEmpty(value) || !Guid.TryParse(value, out var itemId))
        {
            _recipeIngredients[index].InventoryItemId = null;
            return;
        }

        var item = _inventoryItems.FirstOrDefault(x => x.Id == itemId);
        if (item == null) return;

        _recipeIngredients[index].InventoryItemId = itemId;
        _recipeIngredients[index].Name = item.ProductName ?? "";
        _recipeIngredients[index].Unit = item.Unit ?? "";
        _recipeIngredients[index].Cost = item.CostPerUnit ?? 0;
    }

    private void StartEditRecipe(PosDataService.RecipeInfo recipe)
    {
        _editingRecipeId = recipe.Id;
        _selectedProductId = recipe.ProductId;
        _newRecipeName = recipe.Name;
        _newRecipeInstructions = recipe.Instructions ?? "";
        _newRecipePrepTime = recipe.PrepTimeMinutes;
        _recipeIngredients = recipe.Ingredients?.Select(ing => new IngredientRow
        {
            Name = ing.IngredientName,
            Unit = ing.Unit,
            Quantity = ing.Quantity,
            Cost = ing.CostPerUnit,
            InventoryItemId = ing.InventoryItemId,
            QuantityPerServing = ing.QuantityPerServing
        }).ToList() ?? new();
        _showRecipeForm = true;
        _recipeFormMessage = null;
    }

    // ═══ RECIPE CRUD ═══
    private async Task SaveRecipe()
    {
        _recipeFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newRecipeName) || ShopId == Guid.Empty)
        {
            _recipeFormMessage = "Vui lòng nhập tên công thức."; _recipeFormSuccess = false; return;
        }
        try
        {
            var ingredients = _recipeIngredients
                .Where(i => !string.IsNullOrWhiteSpace(i.Name))
                .Select(i => new PosDataService.RecipeIngredientRequest(i.Name, i.Quantity, i.Unit, i.Cost, i.InventoryItemId, i.QuantityPerServing))
                .ToList();
            if (_selectedProductId == Guid.Empty)
            {
                _recipeFormMessage = "Vui lòng chọn sản phẩm liên kết."; _recipeFormSuccess = false; return;
            }
            var req = new PosDataService.CreateRecipeRequest(ShopId, _selectedProductId, _newRecipeName, _newRecipeInstructions, _newRecipePrepTime, ingredients);
            bool ok;
            if (_editingRecipeId.HasValue)
                ok = await DataService.UpdateRecipeAsync(_editingRecipeId.Value, req);
            else
                ok = await DataService.CreateRecipeAsync(req);
            _recipeFormMessage = ok ? (_editingRecipeId.HasValue ? "Đã cập nhật công thức!" : "Đã thêm công thức!") : "Lỗi khi lưu công thức.";
            _recipeFormSuccess = ok;
            if (ok) { _showRecipeForm = false; _editingRecipeId = null; _recipes = await DataService.GetRecipesAsync(ShopId); }
        }
        catch (Exception ex) { _recipeFormMessage = $"Lỗi: {ex.Message}"; _recipeFormSuccess = false; }
    }

    private async Task DeleteRecipeItem(Guid id)
    {
        try
        {
            await DataService.DeleteRecipeAsync(id);
            _recipes = await DataService.GetRecipesAsync(ShopId);
        }
        catch (Exception ex) { _errorMessage = $"Không thể xóa công thức: {ex.Message}"; }
    }

    private RenderFragment RenderEmpty(string icon, string color, string title, string desc, string? ctaIcon = null, string? ctaLabel = null, string? ctaHref = null) => __builder =>
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">@title</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">@desc</p>
            @if (ctaIcon != null && ctaLabel != null)
            {
                <a href="@(ctaHref ?? $"/admin/shop/{ShopId}/menu")" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                    <i data-lucide="@ctaIcon" style="width:16px;height:16px;"></i>
                    @ctaLabel
                </a>
            }
        </div>
    };

    private static string HexToRgb(string hex)
    {
        hex = hex.TrimStart('#');
        if (hex.Length != 6) return "0,0,0";
        return $"{Convert.ToInt32(hex[..2], 16)},{Convert.ToInt32(hex[2..4], 16)},{Convert.ToInt32(hex[4..], 16)}";
    }
}
