@*
    EN: Spa POS Mobile — Single column: categories, service grid, floating appointment button, bottom sheet.
    VI: POS Spa Mobile — Một cột: danh mục, lưới dịch vụ, nút lịch hẹn nổi, sheet dưới.
*@
@page "/pos/{ShopId:guid}/spa/mobile"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="display:flex;flex-direction:column;width:100%;height:100%;overflow:hidden;">
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    @* EN: Category tabs / VI: Tab danh mục *@
    <div class="pos-category-tabs" style="padding:8px 12px;">
        @foreach (var cat in _categories)
        {
            <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                    style="padding:10px 16px;font-size:14px;"
                    @onclick="() => _selectedCategory = cat">
                @cat
            </button>
        }
    </div>

    @* EN: Service grid / VI: Lưới dịch vụ *@
    <div class="pos-product-grid" style="grid-template-columns:repeat(2, 1fr);gap:10px;padding:12px;">
        @foreach (var svc in FilteredServices)
        {
            <div class="pos-product-card" style="padding:10px;" @onclick="() => AddToAppointment(svc)">
                <div class="pos-product-card__image" style="aspect-ratio:1.2;display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="@GetCategoryIcon(svc.Category)" style="width:28px;height:28px;color:var(--pos-text-tertiary);"></i>
                </div>
                <span class="pos-product-card__name" style="font-size:12px;">@svc.Name</span>
                <span class="pos-product-card__price" style="font-size:13px;">@FormatPrice(svc.Price)</span>
                <span style="font-size:10px;color:var(--pos-text-tertiary);">@svc.Duration phút</span>
            </div>
        }
    </div>
    }

    @* EN: Floating appointment button / VI: Nút lịch hẹn nổi *@
    @if (_appointmentItems.Any())
    {
        <button style="position:fixed;bottom:20px;right:20px;width:64px;height:64px;border-radius:50%;background:var(--pos-orange-primary);border:none;color:#fff;font-size:20px;cursor:pointer;box-shadow:0 4px 20px rgba(255,92,0,0.4);display:flex;align-items:center;justify-content:center;z-index:100;"
                @onclick="() => _showSheet = !_showSheet">
            <i data-lucide="calendar-check" style="width:24px;height:24px;"></i>
            <span style="position:absolute;top:-4px;right:-4px;background:var(--pos-danger);color:#fff;font-size:11px;font-weight:700;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;">
                @_appointmentItems.Count
            </span>
        </button>
    }

    @* EN: Bottom sheet appointment / VI: Lịch hẹn dạng sheet dưới *@
    @if (_showSheet)
    {
        <div class="pos-dialog-overlay" @onclick="() => _showSheet = false">
            <div style="position:fixed;bottom:0;left:0;right:0;max-height:70vh;background:var(--pos-bg-elevated);border-radius:20px 20px 0 0;display:flex;flex-direction:column;overflow:hidden;"
                 @onclick:stopPropagation="true">
                @* EN: Handle bar / VI: Thanh kéo *@
                <div style="padding:12px;display:flex;justify-content:center;">
                    <div style="width:40px;height:4px;border-radius:2px;background:var(--pos-border-default);"></div>
                </div>

                <div class="pos-cart-header">
                    <span class="pos-cart-header__title">Lịch hẹn</span>
                    <button style="background:none;border:none;color:var(--pos-danger);font-size:13px;cursor:pointer;"
                            @onclick="() => { _appointmentItems.Clear(); _showSheet = false; }">Xóa</button>
                </div>

                <div class="pos-cart-items" style="max-height:40vh;">
                    @foreach (var item in _appointmentItems)
                    {
                        <div class="pos-cart-item">
                            <div class="pos-cart-item__info">
                                <span class="pos-cart-item__name">@item.Name</span>
                                <div style="display:flex;align-items:center;gap:6px;">
                                    <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                                    <span style="font-size:11px;color:var(--pos-text-tertiary);">@item.Duration phút</span>
                                </div>
                            </div>
                            <button style="background:none;border:none;color:var(--pos-danger);cursor:pointer;font-size:16px;"
                                    @onclick="() => _appointmentItems.Remove(item)">×</button>
                        </div>
                    }
                </div>

                <div class="pos-cart-footer">
                    <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                        <span style="color:var(--pos-text-secondary);">Tổng thời gian</span>
                        <span>@_appointmentItems.Sum(i => i.Duration) phút</span>
                    </div>
                    <div class="pos-cart-total">
                        <span class="pos-cart-total__label">Tổng cộng</span>
                        <span class="pos-cart-total__value">@FormatPrice(AppointmentTotal)</span>
                    </div>
                    <button class="pos-btn-checkout" @onclick="Checkout" disabled="@_isCheckingOut">
                        @(_isCheckingOut ? "Đang xử lý..." : "Thanh toán")
                    </button>
                </div>
            </div>
        </div>
    }
</div>

@code {

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

    // EN: Categories / VI: Danh mục
    private string[] _categories = { "Tất cả" };
    private string _selectedCategory = "Tất cả";
    private bool _showSheet;
    private bool _isCheckingOut;

    // EN: Service list from API / VI: Danh sách dịch vụ từ API
    private List<SpaService> _services = new();

    // EN: Appointment items / VI: Mục lịch hẹn
    private readonly List<AppointmentItem> _appointmentItems = new();
    private IEnumerable<SpaService> FilteredServices =>
        _selectedCategory == "Tất cả" ? _services : _services.Where(s => s.Category == _selectedCategory);
    private decimal AppointmentTotal => _appointmentItems.Sum(i => i.Price);

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

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

            _services = apiProducts.Select(p => new SpaService(
                p.Id,
                p.Name,
                p.Price,
                p.DurationMinutes ?? 60,
                p.Category ?? "Khác"
            )).ToList();

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

    private void AddToAppointment(SpaService svc)
    {
        _appointmentItems.Add(new AppointmentItem(svc.Id, svc.Name, svc.Price, svc.Duration));
    }

    private async Task Checkout()
    {
        if (!_appointmentItems.Any()) return;

        _isCheckingOut = true;
        try
        {
            var orderItems = _appointmentItems.Select(i =>
                new WebClientTpos.Client.Services.PosDataService.PosOrderItemRequest(
                    i.ProductId, i.Name, 1, i.Price, "Service"
                )).ToList();

            var request = new WebClientTpos.Client.Services.PosDataService.CreatePosOrderRequest(
                ShopId, null, orderItems);

            var result = await DataService.CreatePosOrderAsync(request);
            if (result is not null)
            {
                NavigateTo("spa/spa-journey");
            }
        }
        catch
        {
            // EN: Order creation failed / VI: Tạo đơn hàng thất bại
        }
        finally
        {
            _isCheckingOut = false;
        }
    }

    private static string GetCategoryIcon(string category) => category switch
    {
        "Massage" => "hand", "Facial" => "sparkles", "Body" => "bath",
        "Nail" => "paintbrush", "Hair" => "scissors", _ => "heart"
    };

    // EN: Models / VI: Mô hình dữ liệu
    private record SpaService(Guid Id, string Name, decimal Price, int Duration, string Category);
    private record AppointmentItem(Guid ProductId, string Name, decimal Price, int Duration);
}
