@*
    EN: Spa Service Package — Package list with included services, price, savings, expand details, add to appointment.
    VI: Gói dịch vụ Spa — Danh sách gói với dịch vụ bao gồm, giá, tiết kiệm, mở rộng chi tiết, thêm vào lịch hẹn.
*@
@page "/pos/{ShopId:guid}/spa/service-package"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <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;">Gói dịch vụ</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">@_packages.Count gói khả dụng</span>
    </div>

    @* ═══ PACKAGE LIST / DANH SÁCH GÓI ═══ *@
    @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:16px;">
        <div style="display:flex;flex-direction:column;gap:12px;">
            @foreach (var pkg in _packages)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);overflow:hidden;
                            border:1px solid @(_expandedId == pkg.Id ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");">
                    @* EN: Package header / VI: Tiêu đề gói *@
                    <div style="padding:16px;cursor:pointer;" @onclick="() => _expandedId = _expandedId == pkg.Id ? null : pkg.Id">
                        <div style="display:flex;align-items:center;gap:14px;">
                            <div style="width:52px;height:52px;border-radius:14px;background:@pkg.BgColor;
                                        display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                <i data-lucide="@pkg.Icon" style="width:24px;height:24px;color:@pkg.FgColor;"></i>
                            </div>
                            <div style="flex:1;">
                                <div style="display:flex;align-items:center;gap:8px;">
                                    <span style="font-size:16px;font-weight:700;">@pkg.Name</span>
                                    @if (pkg.Popular)
                                    {
                                        <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-top:2px;">
                                    @pkg.ServiceCount dịch vụ • @pkg.TotalDuration phút
                                </div>
                            </div>
                            <div style="text-align:right;flex-shrink:0;">
                                <div style="font-size:18px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(pkg.Price)</div>
                                <div style="font-size:12px;color:#22C55E;font-weight:600;">
                                    Tiết kiệm @FormatPrice(pkg.OriginalPrice - pkg.Price)
                                </div>
                            </div>
                            <i data-lucide="@(_expandedId == pkg.Id ? "chevron-up" : "chevron-down")"
                               style="width:18px;height:18px;color:var(--pos-text-tertiary);flex-shrink:0;"></i>
                        </div>
                    </div>

                    @* EN: Expanded details / VI: Chi tiết mở rộng *@
                    @if (_expandedId == pkg.Id)
                    {
                        <div style="padding:0 16px 16px;border-top:1px solid var(--pos-border-subtle);">
                            <div style="font-size:12px;color:var(--pos-text-tertiary);padding:12px 0 8px;font-weight:600;">
                                DỊCH VỤ BAO GỒM
                            </div>
                            @foreach (var svc in pkg.Services)
                            {
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;
                                            font-size:13px;border-bottom:1px solid var(--pos-border-subtle);">
                                    <div style="display:flex;align-items:center;gap:8px;">
                                        <i data-lucide="check" style="width:14px;height:14px;color:#22C55E;"></i>
                                        <span>@svc.Name</span>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:12px;">
                                        <span style="font-size:11px;color:var(--pos-text-tertiary);">@svc.Duration phút</span>
                                        <span style="font-weight:500;">@FormatPrice(svc.Price)</span>
                                    </div>
                                </div>
                            }

                            @* EN: Price comparison / VI: So sánh giá *@
                            <div style="display:flex;justify-content:space-between;font-size:13px;margin-top:12px;">
                                <span style="color:var(--pos-text-secondary);">Giá lẻ</span>
                                <span style="text-decoration:line-through;color:var(--pos-text-tertiary);">@FormatPrice(pkg.OriginalPrice)</span>
                            </div>
                            <div style="display:flex;justify-content:space-between;font-size:14px;font-weight:600;margin-top:4px;">
                                <span>Giá gói</span>
                                <span style="color:var(--pos-orange-primary);">@FormatPrice(pkg.Price)</span>
                            </div>

                            <button style="width:100%;margin-top:12px;padding:12px;border-radius:var(--pos-radius);
                                           background:var(--pos-orange-primary);border:none;color:#FFF;
                                           cursor:pointer;font-size:14px;font-weight:600;"
                                    @onclick="() => AddPackageToAppointment(pkg)">
                                <i data-lucide="plus" style="width:16px;height:16px;display:inline;"></i> Them vao lich hen
                            </button>
                        </div>
                    }
                </div>
            }
        </div>
    </div>
    }
</div>

@code {

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

    private string? _expandedId = "PKG1";

    // EN: Packages built from DB services / VI: Gói dịch vụ xây dựng từ dữ liệu DB
    private List<PackageInfo> _packages = new();

    // EN: Static package definitions — service groupings are config, prices come from DB
    // VI: Định nghĩa gói tĩnh — nhóm dịch vụ là cấu hình, giá từ DB
    private static readonly List<PackageConfig> PackageConfigs = new()
    {
        new("PKG1", "Gói Thư giãn", 0.857m, true, "leaf", "rgba(34,197,94,.15)", "#22C55E",
            new() { "Massage toàn thân", "Facial cơ bản", "Gội đầu dưỡng sinh" }),
        new("PKG2", "Gói VIP", 0.8m, true, "crown", "rgba(245,158,11,.15)", "#F59E0B",
            new() { "Massage toàn thân", "Facial collagen", "Tắm trắng toàn thân", "Sơn gel", "Gội đầu dưỡng sinh" }),
        new("PKG3", "Gói Cặp đôi", 0.833m, false, "heart", "rgba(239,68,68,.15)", "#EF4444",
            new() { "Massage toàn thân", "Facial cơ bản" }),
        new("PKG4", "Gói Làm đẹp", 0.828m, false, "sparkles", "rgba(139,92,246,.15)", "#8B5CF6",
            new() { "Facial collagen", "Tẩy tế bào chết", "Sơn gel", "Ủ tóc phục hồi" }),
    };

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

        try
        {
            var apiProducts = await DataService.GetProductsAsync(ShopId);
            var productLookup = apiProducts.ToDictionary(p => p.Name, p => p);

            _packages = PackageConfigs.Select(cfg =>
            {
                var services = cfg.ServiceNames.Select(name =>
                {
                    if (productLookup.TryGetValue(name, out var p))
                        return new PackageService(p.Name, p.Price, p.DurationMinutes ?? 60);
                    return new PackageService(name, 0, 0);
                }).ToList();

                // EN: Filter out services with no data (price=0, duration=0)
                // VI: Loc bo dich vu khong co du lieu (gia=0, thoi luong=0)
                var validServices = services.Where(s => s.Price > 0).ToList();
                var originalPrice = validServices.Sum(s => s.Price);
                var packagePrice = originalPrice > 0 ? Math.Round(originalPrice * cfg.DiscountFactor) : 0;
                var totalDuration = services.Sum(s => s.Duration);

                return new PackageInfo(cfg.Id, cfg.Name, packagePrice, originalPrice,
                    validServices.Count > 0 ? validServices.Count : services.Count,
                    totalDuration, cfg.Popular, cfg.Icon, cfg.BgColor, cfg.FgColor, services);
            })
            .Where(p => p.OriginalPrice > 0) // EN: Only show packages with real pricing / VI: Chi hien goi co gia that
            .ToList();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Navigate to appointment booking with selected package services
    // VI: Dieu huong den dat lich hen voi dich vu goi da chon
    private void AddPackageToAppointment(PackageInfo pkg)
    {
        // EN: Navigate to appointment-book page — package info passed via route
        // VI: Chuyen den trang dat lich hen — thong tin goi truyen qua route
        NavigateTo("spa/appointment-book");
    }

    private record PackageConfig(string Id, string Name, decimal DiscountFactor, bool Popular,
        string Icon, string BgColor, string FgColor, List<string> ServiceNames);
    private record PackageService(string Name, decimal Price, int Duration);
    private record PackageInfo(string Id, string Name, decimal Price, decimal OriginalPrice, int ServiceCount,
        int TotalDuration, bool Popular, string Icon, string BgColor, string FgColor, List<PackageService> Services);
}
