@*
    EN: Loyalty Stamp — Customer stamp card: points, stamps grid, reward progress.
        Connected to membership API for customer search and experience management.
    VI: The tich diem — The khach hang: diem, luoi tem, tien trinh thuong.
        Ket noi API thanh vien de tim kiem khach hang va quan ly kinh nghiem.
*@
@page "/pos/{ShopId:guid}/cafe/loyalty-stamp"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div style="display:flex;align-items:center;justify-content:center;height:100%;padding:24px;">
    <div style="width:100%;max-width:480px;">
        @* EN: Customer lookup / VI: Tim khach hang *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
            <div style="display:flex;gap:8px;">
                <input type="text" placeholder="SDT khach hang..." value="@_phone"
                       style="flex:1;padding:12px 16px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:15px;outline:none;"
                       @onchange="@((ChangeEventArgs e) => _phone = e.Value?.ToString() ?? "")" />
                <button style="padding:12px 20px;border-radius:var(--pos-radius);border:none;background:var(--pos-orange-primary);color:#fff;font-size:14px;font-weight:600;cursor:pointer;min-width:80px;"
                        disabled="@_isSearching"
                        @onclick="SearchCustomer">
                    @if (_isSearching)
                    {
                        <span>...</span>
                    }
                    else
                    {
                        <span>Tim</span>
                    }
                </button>
            </div>
            @if (!string.IsNullOrEmpty(_searchError))
            {
                <div style="margin-top:8px;font-size:12px;color:var(--pos-danger);">@_searchError</div>
            }
        </div>

        @if (_customer != null)
        {
        @* EN: Customer info / VI: Thong tin khach hang *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;margin-bottom:16px;text-align:center;">
            <div style="width:64px;height:64px;border-radius:50%;background:var(--pos-orange-primary);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;font-size:24px;font-weight:700;color:#fff;">
                @(_customer.DisplayName ?? "?")[..1]
            </div>
            <div style="font-size:18px;font-weight:600;margin-bottom:4px;">@(_customer.DisplayName ?? "Khach hang")</div>
            <div style="font-size:13px;color:var(--pos-text-tertiary);">@(_customer.Phone ?? _phone)</div>
            <div style="display:flex;justify-content:center;gap:24px;margin-top:16px;">
                <div style="text-align:center;">
                    <div style="font-size:22px;font-weight:700;color:var(--pos-orange-primary);">@_customer.CurrentExp</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);">Diem</div>
                </div>
                <div style="text-align:center;">
                    <div style="font-size:22px;font-weight:700;color:var(--pos-success);">@_customer.TotalExpEarned</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);">Tong diem</div>
                </div>
                <div style="text-align:center;">
                    <div style="font-size:22px;font-weight:700;">@(_customer.LevelName ?? $"Lv.{_customer.CurrentLevel}")</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);">Hang</div>
                </div>
            </div>
        </div>

        @* EN: Stamp grid / VI: Luoi tem *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;margin-bottom:16px;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                <span style="font-size:15px;font-weight:600;">The tich tem</span>
                <span style="font-size:12px;color:var(--pos-text-tertiary);">@_stampCount / @_totalStamps</span>
            </div>
            <div style="display:grid;grid-template-columns:repeat(5, 1fr);gap:10px;">
                @for (int i = 1; i <= _totalStamps; i++)
                {
                    var idx = i;
                    var isStamped = idx <= _stampCount;
                    var isReward = idx == _totalStamps;
                    <div style="aspect-ratio:1;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;
                                background:@(isStamped ? "var(--pos-orange-primary)" : "var(--pos-bg-interactive)");
                                border:@(isReward && !isStamped ? "2px dashed var(--pos-orange-primary)" : "none");
                                color:@(isStamped ? "#fff" : "var(--pos-text-tertiary)");">
                        @if (isReward)
                        {
                            <span>&#127873;</span>
                        }
                        else if (isStamped)
                        {
                            <span>&#9749;</span>
                        }
                        else
                        {
                            <span style="font-size:14px;">@idx</span>
                        }
                    </div>
                }
            </div>

            @* EN: Progress bar / VI: Thanh tien trinh *@
            <div style="margin-top:16px;">
                <div style="height:6px;border-radius:3px;background:var(--pos-bg-interactive);">
                    <div style="height:100%;border-radius:3px;background:var(--pos-orange-primary);width:@(_stampCount * 100 / _totalStamps)%;transition:width 0.3s;"></div>
                </div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:8px;text-align:center;">
                    Con @(_totalStamps - _stampCount) tem nua de nhan 1 ly mien phi!
                </div>
            </div>
        </div>

        @* EN: Add stamp button / VI: Nut them tem *@
        <button class="pos-btn-checkout" disabled="@_isAddingStamp" @onclick="AddStamp">
            @if (_isAddingStamp)
            {
                <span>Dang xu ly...</span>
            }
            else
            {
                <i data-lucide="stamp" style="width:18px;height:18px;"></i>
                <span>Tich tem (+1)</span>
            }
        </button>
        @if (!string.IsNullOrEmpty(_stampMessage))
        {
            <div style="margin-top:8px;text-align:center;font-size:12px;color:var(--pos-success);">@_stampMessage</div>
        }
        }
        else if (!_isSearching && _hasSearched)
        {
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:40px;text-align:center;color:var(--pos-text-tertiary);">
                Khong tim thay khach hang. Hay nhap SDT va nhan Tim.
            </div>
        }
    </div>
</div>

@code {
    // EN: Search state / VI: Trang thai tim kiem
    private string _phone = "";
    private bool _isSearching;
    private bool _hasSearched;
    private string? _searchError;

    // EN: Customer data from API / VI: Du lieu khach hang tu API
    private PosDataService.MemberInfo? _customer;
    private PosDataService.MemberProgressInfo? _progress;

    // EN: Stamp state / VI: Trang thai tem
    private int _totalStamps = 10;
    private int _stampCount;
    private bool _isAddingStamp;
    private string? _stampMessage;

    private async Task SearchCustomer()
    {
        if (string.IsNullOrWhiteSpace(_phone)) return;

        _isSearching = true;
        _searchError = null;
        _stampMessage = null;
        _customer = null;
        _progress = null;
        _hasSearched = true;

        try
        {
            // EN: Search using membership API / VI: Tim kiem su dung API thanh vien
            var members = await DataService.SearchCustomersAsync(ShopId, _phone.Trim());

            if (members.Any())
            {
                _customer = members.First();

                // EN: Load member progress for level info / VI: Tai tien trinh thanh vien cho thong tin hang
                try
                {
                    _progress = await DataService.GetMemberProgressAsync(_customer.Id);
                }
                catch
                {
                    // EN: Progress is optional / VI: Tien trinh la tuy chon
                }

                // EN: Calculate stamps from total exp (1 stamp per 10 exp points)
                // VI: Tinh tem tu tong diem (1 tem moi 10 diem kinh nghiem)
                _stampCount = (_customer.TotalExpEarned / 10) % _totalStamps;
            }
        }
        catch
        {
            _searchError = "Khong the tim kiem. Vui long thu lai.";
        }
        finally
        {
            _isSearching = false;
        }
    }

    private async Task AddStamp()
    {
        if (_customer == null) return;

        _isAddingStamp = true;
        _stampMessage = null;

        try
        {
            // EN: Add experience points via API (10 points = 1 stamp)
            // VI: Them diem kinh nghiem qua API (10 diem = 1 tem)
            var result = await DataService.AddExperienceAsync(_customer.Id, new PosDataService.AddExpRequest(
                Points: 10,
                SourceId: 1, // EN: SourceId 1 = POS purchase / VI: SourceId 1 = Mua hang POS
                ReferenceId: $"stamp-{DateTime.UtcNow:yyyyMMddHHmmss}"
            ));

            if (result != null)
            {
                _stampCount = (result.TotalExpEarned / 10) % _totalStamps;
                _customer = _customer with { CurrentExp = result.CurrentExp, TotalExpEarned = result.TotalExpEarned, CurrentLevel = result.CurrentLevel };

                if (result.LeveledUp)
                {
                    _stampMessage = $"Chuc mung! Khach hang da len hang moi (Level {result.CurrentLevel})!";
                }
                else if (_stampCount == 0)
                {
                    _stampMessage = "Chuc mung! Da tich du tem — 1 ly mien phi!";
                }
                else
                {
                    _stampMessage = "Da tich 1 tem thanh cong!";
                }
            }
            else
            {
                _stampMessage = "Khong the tich tem. Vui long thu lai.";
            }
        }
        catch
        {
            _stampMessage = "Loi khi tich tem. Vui long thu lai.";
        }
        finally
        {
            _isAddingStamp = false;
        }
    }
}
