@*
    EN: Spa Service Combo — Active combos/promotions built from real product data, bundle discounts, apply combo.
    VI: Combo dich vu Spa — Combo/khuyen mai xay dung tu du lieu san pham that, giam gia gop, ap dung.
*@
@page "/pos/{ShopId:guid}/spa/service-combo"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* === HEADER / TIEU DE === *@
    <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <button style="background:var(--pos-bg-interactive);border:none;color:var(--pos-text-primary);
                       padding:8px 12px;border-radius:8px;cursor:pointer;font-size:13px;"
                @onclick="@(() => NavigateTo("spa"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Combo & Khuyen mai</span>
        @if (!_isLoading)
        {
            <span style="font-size:12px;color:var(--pos-text-tertiary);">@_combos.Count combo</span>
        }
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            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
    {
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @* === PROMOTION BANNER / BANNER KHUYEN MAI === *@
        @if (_activePromotion != null)
        {
            <div style="background:linear-gradient(135deg,rgba(255,92,0,.2),rgba(239,68,68,.15));
                        border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;text-align:center;
                        border:1px solid rgba(255,92,0,.3);">
                <div style="font-size:12px;font-weight:600;color:var(--pos-warning);text-transform:uppercase;letter-spacing:1px;">
                    <i data-lucide="zap" style="width:14px;height:14px;display:inline;"></i>
                    @_activePromotion.Name
                </div>
                @if (_activePromotion.EndDate.HasValue)
                {
                    <div style="font-size:14px;font-weight:600;color:var(--pos-orange-primary);margin:8px 0;">
                        Ket thuc: @_activePromotion.EndDate.Value.ToString("dd/MM/yyyy HH:mm")
                    </div>
                }
                <div style="font-size:13px;color:var(--pos-text-secondary);">
                    @(_activePromotion.Description ?? "Giam gia dac biet hom nay!")
                </div>
            </div>
        }

        @* === COMBO LIST / DANH SACH COMBO === *@
        <div style="display:flex;flex-direction:column;gap:12px;">
            @foreach (var combo in _combos)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;
                            border:1px solid @(_selectedCombo == combo.Id ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");">
                    <div style="display:flex;align-items:start;gap:14px;">
                        <div style="width:48px;height:48px;border-radius:12px;background:@combo.BgColor;
                                    display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                            <i data-lucide="@combo.Icon" style="width:22px;height:22px;color:@combo.FgColor;"></i>
                        </div>
                        <div style="flex:1;">
                            <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">
                                <span style="font-size:15px;font-weight:700;">@combo.Name</span>
                                @if (combo.ServiceCount >= 3)
                                {
                                    <span style="font-size:10px;padding:2px 8px;border-radius:4px;font-weight:700;
                                                 background:rgba(255,92,0,.15);color:var(--pos-orange-primary);">HOT</span>
                                }
                            </div>
                            <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:8px;">@combo.Description</div>

                            @* EN: Included services / VI: Dich vu bao gom *@
                            <div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;">
                                @foreach (var svc in combo.Services)
                                {
                                    <span style="font-size:11px;padding:4px 10px;border-radius:6px;
                                                 background:var(--pos-bg-interactive);color:var(--pos-text-secondary);">
                                        @svc
                                    </span>
                                }
                            </div>

                            @* EN: Price comparison / VI: So sanh gia *@
                            <div style="display:flex;align-items:center;gap:12px;">
                                <span style="font-size:13px;text-decoration:line-through;color:var(--pos-text-tertiary);">
                                    @FormatPrice(combo.OriginalPrice)
                                </span>
                                <span style="font-size:18px;font-weight:700;color:var(--pos-orange-primary);">
                                    @FormatPrice(combo.ComboPrice)
                                </span>
                                @if (combo.OriginalPrice > 0)
                                {
                                    <span style="font-size:12px;color:#22C55E;font-weight:600;">
                                        -@(Math.Round((combo.OriginalPrice - combo.ComboPrice) * 100 / combo.OriginalPrice))%
                                    </span>
                                }
                            </div>
                        </div>
                    </div>

                    @* EN: Apply button / VI: Nut ap dung *@
                    <button style="width:100%;margin-top:12px;padding:10px;border-radius:var(--pos-radius);
                                   background:@(_selectedCombo == combo.Id ? "var(--pos-success)" : "var(--pos-bg-interactive)");
                                   border:1px solid @(_selectedCombo == combo.Id ? "var(--pos-success)" : "var(--pos-border-default)");
                                   color:@(_selectedCombo == combo.Id ? "#FFF" : "var(--pos-text-primary)");
                                   cursor:pointer;font-size:13px;font-weight:600;"
                            @onclick="() => _selectedCombo = _selectedCombo == combo.Id ? null : combo.Id">
                        @if (_selectedCombo == combo.Id)
                        {
                            <i data-lucide="check" style="width:14px;height:14px;display:inline;"></i>
                            <span> Da chon</span>
                        }
                        else
                        {
                            <span>Ap dung combo</span>
                        }
                    </button>
                </div>
            }
        </div>

        @if (!_combos.Any())
        {
            <div style="text-align:center;padding:40px;color:var(--pos-text-tertiary);">
                <i data-lucide="package" style="width:48px;height:48px;display:block;margin:0 auto 12px;opacity:0.3;"></i>
                Chua co combo nao. Them san pham de tao combo tu dong.
            </div>
        }
    </div>

    @* === FOOTER / CHAN TRANG === *@
    @if (_selectedCombo is not null)
    {
        <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);flex-shrink:0;">
            <button class="pos-btn-checkout" @onclick="@(() => NavigateTo("spa/appointment-book"))">
                <i data-lucide="arrow-right" style="width:18px;height:18px;"></i> Tiep tuc voi combo da chon
            </button>
        </div>
    }
    }
</div>

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

    private string? _selectedCombo;

    // EN: Combos built from product data / VI: Combo xay dung tu du lieu san pham
    private List<ComboInfo> _combos = new();

    // EN: Active promotion from API / VI: Khuyen mai dang ap dung tu API
    private WebClientTpos.Client.Services.PosDataService.PromotionInfo? _activePromotion;

    // EN: Combo definitions — groups of services that form combos
    // VI: Dinh nghia combo — nhom dich vu tao thanh combo
    private static readonly List<ComboConfig> ComboConfigs = new()
    {
        new("CB1", "Mua 2 tang 1", "Mua 2 dich vu Massage bat ky, tang 1 Massage chan mien phi",
            0.75m, "gift", "rgba(255,92,0,.15)", "#FF5C00",
            new() { "Massage", "massage" }),
        new("CB2", "Combo Spa Day", "Tron goi thu gian ca ngay: Massage + Facial + Nail",
            0.79m, "sun", "rgba(245,158,11,.15)", "#F59E0B",
            new() { "Massage", "Facial", "Nail", "Son" }),
        new("CB3", "Combo Lam dep", "Cham soc da + Tam trang gia dac biet",
            0.80m, "sparkles", "rgba(139,92,246,.15)", "#8B5CF6",
            new() { "Tam", "Tay te bao", "Facial" }),
    };

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

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

            // EN: Try to load promotions / VI: Thu tai khuyen mai
            try
            {
                var promos = await DataService.GetPromotionsAsync();
                _activePromotion = promos
                    .Where(p => p.IsActive && (!p.EndDate.HasValue || p.EndDate > DateTime.Now))
                    .FirstOrDefault();
            }
            catch { /* EN: No promotions available / VI: Khong co khuyen mai */ }

            // EN: Build combos from real products / VI: Xay dung combo tu san pham that
            if (products.Any())
            {
                _combos = ComboConfigs.Select((cfg, idx) =>
                {
                    // EN: Find products matching combo keywords / VI: Tim san pham khop voi tu khoa combo
                    var matchedProducts = products
                        .Where(p => cfg.Keywords.Any(k =>
                            p.Name.Contains(k, StringComparison.OrdinalIgnoreCase) ||
                            (p.CategoryName?.Contains(k, StringComparison.OrdinalIgnoreCase) ?? false)))
                        .Take(4)
                        .ToList();

                    if (!matchedProducts.Any())
                    {
                        // EN: Fallback — use random products for this combo / VI: Du phong — dung san pham ngau nhien
                        matchedProducts = products.Skip(idx * 2).Take(3).ToList();
                    }

                    var serviceNames = matchedProducts.Select(p => p.Name).ToList();
                    var originalPrice = matchedProducts.Sum(p => p.Price);
                    var comboPrice = Math.Round(originalPrice * cfg.DiscountFactor);

                    return new ComboInfo(cfg.Id, cfg.Name, cfg.Description,
                        originalPrice, comboPrice, serviceNames.Count,
                        cfg.Icon, cfg.BgColor, cfg.FgColor, serviceNames);
                })
                .Where(c => c.OriginalPrice > 0)
                .ToList();
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private record ComboConfig(string Id, string Name, string Description, decimal DiscountFactor,
        string Icon, string BgColor, string FgColor, List<string> Keywords);
    private record ComboInfo(string Id, string Name, string Description, decimal OriginalPrice,
        decimal ComboPrice, int ServiceCount, string Icon, string BgColor, string FgColor, List<string> Services);
}
