@*
    EN: Beauty Salon POS Tablet — 2-column layout: service grid + appointment sidebar (340px), touch-friendly.
    VI: POS Tham My Tablet — Bo cuc 2 cot: luoi dich vu + sidebar lich hen (340px), than thien cam ung.
*@
@page "/pos/{ShopId:guid}/beauty/tablet"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

@* === SERVICE PANEL / PANEL DICH VU === *@
<div class="pos-product-panel">
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Khong the tai du lieu
        </div>
    }
    else
    {
    <div class="pos-category-tabs">
        @foreach (var cat in _categories)
        {
            <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                    style="padding:12px 20px;font-size:15px;@(cat == _selectedCategory ? "background:#A855F7;color:#fff;" : "")"
                    @onclick="() => _selectedCategory = cat">
                @cat
            </button>
        }
    </div>

    <div class="pos-product-grid" style="grid-template-columns:repeat(auto-fill, minmax(160px, 1fr));gap:16px;padding:20px;">
        @foreach (var svc in FilteredServices)
        {
            <div class="pos-product-card" style="padding:16px;" @onclick="() => AddToAppointment(svc)">
                <div class="pos-product-card__image" style="display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="@GetCategoryIcon(svc.Category)" style="width:36px;height:36px;color:#A855F7;"></i>
                </div>
                <span class="pos-product-card__name" style="font-size:15px;">@svc.Name</span>
                <span class="pos-product-card__price" style="font-size:16px;">@FormatPrice(svc.Price)</span>
                <span style="font-size:12px;color:var(--pos-text-tertiary);">
                    <i data-lucide="clock" style="width:11px;height:11px;display:inline;"></i> @svc.Duration phut
                </span>
            </div>
        }
    </div>
    }
</div>

@* === APPOINTMENT SIDEBAR / SIDEBAR LICH HEN === *@
<div class="pos-cart-panel" style="width:340px;min-width:340px;">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title" style="font-size:17px;">
            <i data-lucide="scissors" style="width:18px;height:18px;display:inline;color:#A855F7;"></i>
            Dich Vu Tham My
        </span>
        <button style="background:none;border:none;color:var(--pos-danger);font-size:13px;cursor:pointer;"
                @onclick="() => _appointmentItems.Clear()">Xoa tat ca</button>
    </div>

    @* EN: Customer selection / VI: Chon khach hang *@
    <div style="padding:10px 12px;border-bottom:1px solid var(--pos-border-subtle);">
        <button style="width:100%;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);border:1px dashed var(--pos-border-default);color:var(--pos-text-tertiary);cursor:pointer;font-size:14px;"
                @onclick="@(() => NavigateTo("beauty/consent-form"))">
            <i data-lucide="user-plus" style="width:16px;height:16px;display:inline;"></i> Chon khach hang
        </button>
    </div>

    <div class="pos-cart-items">
        @foreach (var item in _appointmentItems)
        {
            <div class="pos-cart-item" style="padding:14px 12px;">
                <div class="pos-cart-item__info">
                    <span class="pos-cart-item__name" style="font-size:15px;">@item.Name</span>
                    <div style="display:flex;align-items:center;gap:8px;">
                        <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                        <span style="font-size:11px;color:var(--pos-text-tertiary);">@item.Duration phut</span>
                    </div>
                </div>
                <button style="width:36px;height:36px;border-radius:10px;border:1px solid var(--pos-border-default);background:transparent;color:var(--pos-danger);font-size:18px;cursor:pointer;"
                        @onclick="() => _appointmentItems.Remove(item)">x</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);">Tong thoi gian</span>
            <span>@_appointmentItems.Sum(i => i.Duration) phut</span>
        </div>
        <div class="pos-cart-total">
            <span class="pos-cart-total__label">Tong cong</span>
            <span class="pos-cart-total__value">@FormatPrice(AppointmentTotal)</span>
        </div>

        @* EN: Consent check / VI: Kiem tra dong y *@
        <div style="display:flex;align-items:center;gap:8px;padding:8px 0;font-size:13px;">
            <input type="checkbox" @bind="_consentChecked"
                   style="width:18px;height:18px;accent-color:#A855F7;" />
            <span style="color:var(--pos-text-secondary);">
                <i data-lucide="clipboard-check" style="width:14px;height:14px;display:inline;color:#A855F7;"></i>
                Phieu dong y da ky
            </span>
            <button style="margin-left:auto;background:none;border:none;color:#A855F7;cursor:pointer;font-size:12px;text-decoration:underline;"
                    @onclick="@(() => NavigateTo("beauty/consent-form"))">
                Tao phieu
            </button>
        </div>

        <button class="pos-btn-checkout" style="height:56px;font-size:17px;background:#A855F7;" @onclick="Checkout"
                disabled="@(_isCheckingOut || !_consentChecked)">
            @(_isCheckingOut ? "Dang xu ly..." : $"Thanh toan — {FormatPrice(AppointmentTotal)}")
        </button>
    </div>
</div>

@code {

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

    // EN: Categories / VI: Danh muc
    private string[] _categories = { "Tat ca" };
    private string _selectedCategory = "Tat ca";
    private bool _consentChecked;
    private bool _isCheckingOut;

    // EN: Service list from API / VI: Danh sach dich vu tu API
    private List<BeautyService> _services = new();

    // EN: Appointment items / VI: Muc lich hen
    private readonly List<AppointmentItem> _appointmentItems = new();
    private IEnumerable<BeautyService> FilteredServices =>
        _selectedCategory == "Tat ca" ? _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 BeautyService(
                p.Id,
                p.Name,
                p.Price,
                p.DurationMinutes ?? 60,
                p.Category ?? "Khac"
            )).ToList();

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

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

    private async Task Checkout()
    {
        if (!_appointmentItems.Any() || !_consentChecked) 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("beauty/follow-up");
            }
        }
        catch
        {
            // EN: Order creation failed / VI: Tao don hang that bai
        }
        finally
        {
            _isCheckingOut = false;
        }
    }

    private static string GetCategoryIcon(string category) => category switch
    {
        "Botox" => "syringe", "Filler" => "droplets", "Laser" => "zap",
        "Skincare" => "sparkles", "Phau thuat" => "stethoscope", _ => "scissors"
    };

    // EN: Models / VI: Mo hinh du lieu
    private record BeautyService(Guid Id, string Name, decimal Price, int Duration, string Category);
    private record AppointmentItem(Guid ProductId, string Name, decimal Price, int Duration);
}
