@*
    EN: Stamp Card — Visual stamp card with customer lookup, stamp grid, reward claim flow.
        Connected to membership-service stamp card API for real stamp card management.
    VI: The Tich Diem — The tem truc quan voi tim kiem khach hang, luoi tem, quy trinh nhan thuong.
        Ket noi API the tem cua membership-service de quan ly the tem thuc.
*@
@page "/pos/{ShopId:guid}/cafe/stamps"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div style="display:flex;align-items:flex-start;justify-content:center;height:100%;padding:24px;overflow-y:auto;">
    <div style="width:100%;max-width:520px;">

        @* ═══ HEADER / TIEU DE ═══ *@
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">
            <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("cafe"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:18px;font-weight:700;">The tich diem</span>
        </div>

        @* ═══ CUSTOMER LOOKUP / TIM KHACH HANG ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
            <div style="font-size:13px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:10px;">Tim khach hang</div>
            <div style="display:flex;gap:8px;">
                <input type="text" placeholder="SDT hoac ma thanh vien..." value="@_searchQuery"
                       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) => _searchQuery = e.Value?.ToString() ?? "")"
                       @onkeydown="@(async (e) => { if (e.Key == "Enter") await SearchCustomerAsync(); })" />
                <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="SearchCustomerAsync">
                    @(_isSearching ? "..." : "Tim")
                </button>
            </div>
            @if (!string.IsNullOrEmpty(_searchError))
            {
                <div style="margin-top:8px;font-size:12px;color:var(--pos-danger);">@_searchError</div>
            }
        </div>

        @if (_customer != null && _stampCard != null)
        {
            @* ═══ CUSTOMER INFO / 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:56px;height:56px;border-radius:50%;background:var(--pos-orange-primary);
                            display:flex;align-items:center;justify-content:center;margin:0 auto 12px;
                            font-size:22px;font-weight:700;color:#fff;">
                    @((_customer.DisplayName ?? "?")[..1].ToUpper())
                </div>
                <div style="font-size:17px;font-weight:600;margin-bottom:2px;">@(_customer.DisplayName ?? "Khach hang")</div>
                <div style="font-size:13px;color:var(--pos-text-tertiary);margin-bottom:4px;">@(_customer.Phone ?? _searchQuery)</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);">@_stampCard.CardName</div>
            </div>

            @* ═══ STAMP GRID / 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:13px;color:var(--pos-text-tertiary);font-weight:600;">
                        @_stampCard.CurrentStamps / @_stampCard.TotalStampsRequired
                    </span>
                </div>

                @* EN: Visual stamp circles / VI: Cac vong tron tem truc quan *@
                <div style="display:grid;grid-template-columns:repeat(5, 1fr);gap:10px;">
                    @for (int i = 1; i <= _stampCard.TotalStampsRequired; i++)
                    {
                        var idx = i;
                        var isStamped = idx <= _stampCard.CurrentStamps;
                        var isReward = idx == _stampCard.TotalStampsRequired;
                        var isNewlyAdded = idx == _stampCard.CurrentStamps && _justAddedStamp;

                        <div style="aspect-ratio:1;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;
                                    transition:all 0.4s ease;
                                    @(isNewlyAdded ? "transform:scale(1.15);box-shadow:0 0 12px rgba(255,92,0,0.5);" : "")
                                    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 && !isStamped)
                            {
                                <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:@(_stampCard.TotalStampsRequired > 0 ? _stampCard.CurrentStamps * 100 / _stampCard.TotalStampsRequired : 0)%;
                                    transition:width 0.4s ease;"></div>
                    </div>
                    @if (!_stampCard.IsCompleted)
                    {
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:8px;text-align:center;">
                            Con @(_stampCard.TotalStampsRequired - _stampCard.CurrentStamps) tem nua de nhan 1 ly mien phi!
                        </div>
                    }
                </div>
            </div>

            @* ═══ REWARD / ACTION SECTION ═══ *@
            @if (_stampCard.IsCompleted && !_stampCard.RewardClaimed)
            {
                @* EN: Card complete — show celebration + claim button *@
                <div style="background:linear-gradient(135deg, rgba(255,92,0,0.15), rgba(245,158,11,0.15));
                            border:1px solid var(--pos-orange-primary);border-radius:var(--pos-radius);padding:24px;
                            margin-bottom:16px;text-align:center;">
                    <div style="font-size:28px;margin-bottom:8px;">&#127881;</div>
                    <div style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);margin-bottom:4px;">
                        Chuc mung! Da du tem!
                    </div>
                    <div style="font-size:13px;color:var(--pos-text-secondary);margin-bottom:16px;">
                        Khach hang du dieu kien nhan 1 ly mien phi.
                    </div>
                    <button class="pos-btn-checkout" disabled="@_isClaiming" @onclick="ClaimRewardAsync"
                            style="background:var(--pos-success);">
                        @if (_isClaiming)
                        {
                            <span>Dang xu ly...</span>
                        }
                        else
                        {
                            <i data-lucide="gift" style="width:18px;height:18px;"></i>
                            <span>Nhan thuong</span>
                        }
                    </button>
                </div>
            }
            else if (_stampCard.RewardClaimed)
            {
                @* EN: Reward already claimed — show reset option *@
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;
                            margin-bottom:16px;text-align:center;">
                    <div style="font-size:24px;margin-bottom:8px;">&#9989;</div>
                    <div style="font-size:14px;color:var(--pos-success);font-weight:600;margin-bottom:4px;">
                        Da nhan thuong thanh cong!
                    </div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:16px;">
                        The tem da hoan tat. Tim khach hang moi hoac bat dau lai.
                    </div>
                    <button style="padding:12px 24px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                   background:transparent;color:var(--pos-text-secondary);cursor:pointer;font-size:14px;font-weight:600;"
                            @onclick="ResetSearch">
                        <i data-lucide="refresh-cw" style="width:14px;height:14px;display:inline;"></i>
                        Bat dau lai
                    </button>
                </div>
            }
            else
            {
                @* EN: Normal state — add stamp button *@
                <button class="pos-btn-checkout" disabled="@_isAddingStamp" @onclick="AddStampAsync">
                    @if (_isAddingStamp)
                    {
                        <span>Dang xu ly...</span>
                    }
                    else
                    {
                        <i data-lucide="stamp" style="width:18px;height:18px;"></i>
                        <span>Them tem (+1)</span>
                    }
                </button>
            }

            @if (!string.IsNullOrEmpty(_actionMessage))
            {
                <div style="margin-top:8px;text-align:center;font-size:13px;
                            color:@(_actionIsError ? "var(--pos-danger)" : "var(--pos-success)");">
                    @_actionMessage
                </div>
            }

            @* ═══ STAMP HISTORY / LICH SU TICH TEM ═══ *@
            @if (_expHistory.Any())
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-top:16px;">
                    <div style="font-size:13px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:12px;">
                        Lich su tich tem gan day
                    </div>
                    @foreach (var tx in _expHistory.Take(5))
                    {
                        <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;
                                    border-bottom:1px solid var(--pos-border-subtle);">
                            <div>
                                <div style="font-size:13px;color:var(--pos-text-primary);">+@tx.Points diem</div>
                                <div style="font-size:11px;color:var(--pos-text-tertiary);">@tx.CreatedAt.ToString("dd/MM/yyyy HH:mm")</div>
                            </div>
                            @if (!string.IsNullOrEmpty(tx.ReferenceId))
                            {
                                <div style="font-size:11px;color:var(--pos-text-tertiary);font-family:monospace;">
                                    @tx.ReferenceId[..Math.Min(12, tx.ReferenceId.Length)]
                                </div>
                            }
                        </div>
                    }
                </div>
            }
        }
        else if (!_isSearching && _hasSearched)
        {
            @* EN: No customer found / VI: Khong tim thay khach hang *@
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:40px;
                        text-align:center;color:var(--pos-text-tertiary);">
                <div style="font-size:32px;margin-bottom:12px;">&#128269;</div>
                <div>Khong tim thay khach hang. Hay nhap SDT va nhan Tim.</div>
            </div>
        }
    </div>
</div>

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

    // EN: Customer and stamp card data / VI: Du lieu khach hang va the tem
    private PosDataService.MemberInfo? _customer;
    private PosDataService.StampCardInfo? _stampCard;
    private List<PosDataService.ExpTransactionInfo> _expHistory = new();

    // EN: Action state / VI: Trang thai hanh dong
    private bool _isAddingStamp;
    private bool _isClaiming;
    private bool _justAddedStamp;
    private string? _actionMessage;
    private bool _actionIsError;

    /// <summary>
    /// EN: Search for customer by phone or member ID.
    /// VI: Tim kiem khach hang theo SDT hoac ma thanh vien.
    /// </summary>
    private async Task SearchCustomerAsync()
    {
        if (string.IsNullOrWhiteSpace(_searchQuery)) return;

        _isSearching = true;
        _searchError = null;
        _actionMessage = null;
        _customer = null;
        _stampCard = null;
        _expHistory = new();
        _hasSearched = true;
        _justAddedStamp = false;

        try
        {
            var members = await DataService.SearchCustomersAsync(ShopId, _searchQuery.Trim());
            if (members.Any())
            {
                _customer = members.First();

                // EN: Try to load real stamp card from membership-service
                // VI: Thu tai the tem thuc tu membership-service
                _stampCard = await DataService.GetStampCardAsync(ShopId, _customer.Id);

                // EN: Fallback — synthesize a stamp card from experience points if API not ready
                // VI: Du phong — tao the tem tu diem kinh nghiem neu API chua san sang
                if (_stampCard == null)
                {
                    var totalStamps = 10;
                    var currentStamps = (_customer.TotalExpEarned / 10) % totalStamps;
                    var isComplete = currentStamps == 0 && _customer.TotalExpEarned > 0;
                    _stampCard = new PosDataService.StampCardInfo(
                        Guid.Empty, _customer.Id, "The Tich Tem Cafe",
                        totalStamps, isComplete ? totalStamps : currentStamps,
                        isComplete, false);
                }

                // EN: Load recent stamp history
                // VI: Tai lich su tich tem gan day
                try { _expHistory = await DataService.GetExperienceHistoryAsync(_customer.Id); }
                catch { /* optional data */ }
            }
        }
        catch
        {
            _searchError = "Khong the tim kiem. Vui long thu lai.";
        }
        finally
        {
            _isSearching = false;
        }
    }

    /// <summary>
    /// EN: Add one stamp to the customer's card.
    /// VI: Them mot tem vao the khach hang.
    /// </summary>
    private async Task AddStampAsync()
    {
        if (_customer == null || _stampCard == null) return;

        _isAddingStamp = true;
        _actionMessage = null;
        _actionIsError = false;
        _justAddedStamp = false;

        try
        {
            // EN: Try real stamp card API first
            // VI: Thu API the tem thuc truoc
            var updated = await DataService.AddStampAsync(ShopId, _customer.Id);
            if (updated != null)
            {
                _stampCard = updated;
                _justAddedStamp = true;
                _actionMessage = updated.IsCompleted
                    ? "Da tich du tem! Khach hang co the nhan thuong."
                    : "Da tich 1 tem thanh cong!";
            }
            else
            {
                // EN: Fallback — add via experience API
                // VI: Du phong — them qua API kinh nghiem
                var result = await DataService.AddExperienceAsync(_customer.Id, new PosDataService.AddExpRequest(
                    Points: 10, SourceId: 1,
                    ReferenceId: $"stamp-{DateTime.UtcNow:yyyyMMddHHmmss}"));

                if (result != null)
                {
                    var currentStamps = (result.TotalExpEarned / 10) % _stampCard.TotalStampsRequired;
                    var isComplete = currentStamps == 0 && result.TotalExpEarned > 0;
                    _stampCard = _stampCard with
                    {
                        CurrentStamps = isComplete ? _stampCard.TotalStampsRequired : currentStamps,
                        IsCompleted = isComplete
                    };
                    _customer = _customer with { CurrentExp = result.CurrentExp, TotalExpEarned = result.TotalExpEarned };
                    _justAddedStamp = true;

                    _actionMessage = isComplete
                        ? "Da tich du tem! Khach hang co the nhan thuong."
                        : result.LeveledUp
                            ? $"Da tich tem + len hang moi (Level {result.CurrentLevel})!"
                            : "Da tich 1 tem thanh cong!";
                }
                else
                {
                    _actionMessage = "Khong the tich tem. Vui long thu lai.";
                    _actionIsError = true;
                }
            }

            // EN: Refresh history
            // VI: Lam moi lich su
            try { _expHistory = await DataService.GetExperienceHistoryAsync(_customer.Id); }
            catch { }
        }
        catch
        {
            _actionMessage = "Loi khi tich tem. Vui long thu lai.";
            _actionIsError = true;
        }
        finally
        {
            _isAddingStamp = false;
        }
    }

    /// <summary>
    /// EN: Claim the reward for a completed stamp card.
    /// VI: Nhan thuong cho the tem da hoan tat.
    /// </summary>
    private async Task ClaimRewardAsync()
    {
        if (_stampCard == null) return;

        _isClaiming = true;
        _actionMessage = null;
        _actionIsError = false;

        try
        {
            var success = await DataService.ClaimRewardAsync(_stampCard.Id);
            if (success)
            {
                _stampCard = _stampCard with { RewardClaimed = true };
                _actionMessage = "Nhan thuong thanh cong! Khach hang duoc 1 ly mien phi.";
            }
            else
            {
                _actionMessage = "Khong the nhan thuong. Vui long thu lai.";
                _actionIsError = true;
            }
        }
        catch
        {
            _actionMessage = "Loi khi nhan thuong. Vui long thu lai.";
            _actionIsError = true;
        }
        finally
        {
            _isClaiming = false;
        }
    }

    /// <summary>
    /// EN: Reset search state for a new customer.
    /// VI: Xoa trang thai tim kiem cho khach hang moi.
    /// </summary>
    private void ResetSearch()
    {
        _searchQuery = "";
        _customer = null;
        _stampCard = null;
        _expHistory = new();
        _hasSearched = false;
        _actionMessage = null;
        _justAddedStamp = false;
    }
}
