@*
    EN: Beauty Salon POS Desktop — 2-panel layout: service categories + grid (left), current appointment/bill (right).
    VI: POS Tham My Desktop — Bo cuc 2 panel: danh muc dich vu + luoi (trai), lich hen/hoa don hien tai (phai).
*@
@page "/pos/{ShopId:guid}/beauty"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

@* === SERVICE PANEL (LEFT) / PANEL DICH VU (TRAI) === *@
<div class="pos-product-panel" style="padding:16px;overflow-y:auto;">
    @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
    {
        @* EN: Category tabs / VI: Tab danh muc *@
        <div class="pos-category-tabs">
            @foreach (var cat in _categories)
            {
                <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                        style="@(cat == _selectedCategory ? "background:#A855F7;color:#fff;" : "")"
                        @onclick="() => _selectedCategory = cat">
                    @cat
                </button>
            }
        </div>

        @* === SERVICE GRID / LUOI DICH VU === *@
        @if (!_services.Any())
        {
            <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:60px 0;color:var(--pos-text-tertiary);">
                <i data-lucide="scissors" style="width:48px;height:48px;margin-bottom:12px;opacity:0.3;"></i>
                <div style="font-size:15px;font-weight:600;margin-bottom:4px;">Chua co dich vu nao</div>
                <div style="font-size:13px;">Vui long them dich vu trong phan Quan ly cua hang</div>
            </div>
        }
        else
        {
        <div class="pos-product-grid">
            @foreach (var svc in FilteredServices)
            {
                <div class="pos-product-card" @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:32px;height:32px;color:#A855F7;"></i>
                    </div>
                    <span class="pos-product-card__name">@svc.Name</span>
                    <span class="pos-product-card__price">@FormatPrice(svc.Price)</span>
                    <span style="font-size:11px;color:var(--pos-text-tertiary);">
                        <i data-lucide="clock" style="width:10px;height:10px;display:inline;"></i> @svc.Duration phut
                    </span>
                </div>
            }
        </div>
        }
    }
</div>

@* === APPOINTMENT PANEL (RIGHT) / PANEL LICH HEN (PHAI) === *@
<div class="pos-cart-panel">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title">
            <i data-lucide="scissors" style="width:18px;height:18px;display:inline;color:#A855F7;"></i>
            Dich Vu Tham My
        </span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">@_appointmentItems.Count dich vu</span>
    </div>

    @* EN: Customer info / VI: Thong tin khach *@
    @if (_customerName is not null)
    {
        <div style="padding:8px 12px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--pos-border-subtle);">
            <div style="width:36px;height:36px;border-radius:50%;background:#A855F7;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#fff;">
                @_customerName[..1]
            </div>
            <div>
                <div style="font-size:13px;font-weight:600;">@_customerName</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);">@_customerPhone</div>
            </div>
        </div>
    }
    else
    {
        <div style="padding:8px 12px;border-bottom:1px solid var(--pos-border-subtle);">
            <button style="width:100%;padding:10px;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:13px;"
                    @onclick="@(() => NavigateTo("beauty/consent-form"))">
                <i data-lucide="user-plus" style="width:14px;height:14px;display:inline;"></i> Chon khach hang
            </button>
        </div>
    }

    <div class="pos-cart-items">
        @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: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>
                <div class="pos-cart-item__qty">
                    <button @onclick="() => RemoveItem(item)">
                        <i data-lucide="x" style="width:14px;height:14px;"></i>
                    </button>
                </div>
            </div>
        }
    </div>

    <div class="pos-cart-footer">
        @* EN: Duration total / VI: Tong thoi gian *@
        <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 form requirement / VI: Yeu cau phieu dong y *@
        <div style="display:flex;align-items:center;gap:8px;padding:8px 0;font-size:13px;">
            <input type="checkbox" id="consentCheck" @bind="_consentChecked"
                   style="width:18px;height:18px;accent-color:#A855F7;cursor:pointer;" />
            <label for="consentCheck" style="color:var(--pos-text-secondary);cursor:pointer;">
                <i data-lucide="clipboard-check" style="width:14px;height:14px;display:inline;color:#A855F7;"></i>
                Phieu dong y da ky
            </label>
            <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>

        <div style="display:flex;gap:8px;">
            <button style="flex:1;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;font-weight:600;"
                    @onclick="@(() => NavigateTo("beauty/treatment-plan"))">
                <i data-lucide="clipboard-list" style="width:16px;height:16px;display:inline;"></i> Phac do
            </button>
            <button style="flex:1;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;font-weight:600;"
                    @onclick="@(() => NavigateTo("beauty/doctor-schedule"))">
                <i data-lucide="calendar" style="width:16px;height:16px;display:inline;"></i> Dat lich
            </button>
            <button class="pos-btn-checkout" style="flex:1;background:#A855F7;" @onclick="Checkout"
                    disabled="@(_isCheckingOut || !_consentChecked)">
                <i data-lucide="credit-card" style="width:18px;height:18px;"></i> @(_isCheckingOut ? "Dang xu ly..." : "Thanh toan")
            </button>
        </div>
    </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";

    // EN: Customer info / VI: Thong tin khach hang
    private string? _customerName;
    private string _customerPhone = "";
    private bool _isCheckingOut;
    private bool _consentChecked;

    // 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 void RemoveItem(AppointmentItem item) => _appointmentItems.Remove(item);

    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);
}
