@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService

<div style="display:flex;flex-direction:column;height:calc(100vh - 180px);background:var(--admin-bg-page);border-radius:12px;border:1px solid var(--admin-border-subtle);overflow:hidden;">
    @* Header *@
    <div style="padding:16px 20px;border-bottom:1px solid var(--admin-border-subtle);display:flex;align-items:center;justify-content:space-between;">
        <div style="display:flex;align-items:center;gap:10px;">
            <div style="width:36px;height:36px;border-radius:10px;background:rgba(255,92,0,0.1);display:flex;align-items:center;justify-content:center;">
                <i data-lucide="bot" style="width:20px;height:20px;color:var(--admin-orange-primary);"></i>
            </div>
            <div>
                <div style="font-size:15px;font-weight:700;">AI Assistant</div>
                <div style="font-size:11px;color:var(--admin-text-tertiary);">Trợ lý AI quản lý cửa hàng</div>
            </div>
        </div>
        <button @onclick="ClearChat" style="padding:6px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-tertiary);font-size:12px;cursor:pointer;display:flex;align-items:center;gap:4px;">
            <i data-lucide="trash-2" style="width:14px;height:14px;"></i> Xóa
        </button>
    </div>

    @* Messages *@
    <div style="flex:1;overflow-y:auto;padding:20px;display:flex;flex-direction:column;gap:16px;" id="ai-chat-messages">
        @if (!_messages.Any())
        {
            @* Empty state with suggested prompts *@
            <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;">
                <div style="width:64px;height:64px;border-radius:20px;background:rgba(255,92,0,0.08);display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="sparkles" style="width:32px;height:32px;color:var(--admin-orange-primary);"></i>
                </div>
                <div style="text-align:center;">
                    <div style="font-size:16px;font-weight:700;margin-bottom:4px;">Xin chào! Tôi là AI Assistant</div>
                    <div style="font-size:13px;color:var(--admin-text-tertiary);">Tôi có thể giúp quản lý sản phẩm, tồn kho, công thức và phân tích doanh thu.</div>
                </div>
                <div style="display:flex;flex-wrap:wrap;gap:8px;justify-content:center;max-width:500px;">
                    @foreach (var (icon, text) in _suggestions)
                    {
                        <button @onclick="@(() => SendSuggestion(text))" style="padding:8px 14px;border-radius:20px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-secondary);font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;transition:border-color 0.2s;">
                            <i data-lucide="@icon" style="width:14px;height:14px;color:var(--admin-orange-primary);"></i> @text
                        </button>
                    }
                </div>
            </div>
        }
        @foreach (var msg in _messages)
        {
            @if (msg.Role == "user")
            {
                <div style="display:flex;justify-content:flex-end;">
                    <div style="max-width:70%;padding:12px 16px;border-radius:16px 16px 4px 16px;background:rgba(255,92,0,0.12);color:var(--admin-text-primary);font-size:14px;line-height:1.5;">
                        @msg.Content
                    </div>
                </div>
            }
            else
            {
                <div style="display:flex;gap:10px;">
                    <div style="width:28px;height:28px;border-radius:8px;background:rgba(255,92,0,0.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;margin-top:2px;">
                        <i data-lucide="bot" style="width:16px;height:16px;color:var(--admin-orange-primary);"></i>
                    </div>
                    <div style="max-width:75%;">
                        <div style="padding:12px 16px;border-radius:4px 16px 16px 16px;background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:14px;line-height:1.6;white-space:pre-wrap;">@msg.Content</div>
                        @if (msg.ToolsUsed?.Any() == true)
                        {
                            <div style="display:flex;flex-wrap:wrap;gap:4px;margin-top:6px;">
                                @foreach (var tool in msg.ToolsUsed)
                                {
                                    <span style="font-size:10px;padding:2px 8px;border-radius:4px;background:rgba(34,197,94,0.1);color:#22C55E;">@tool</span>
                                }
                            </div>
                        }
                    </div>
                </div>
            }
        }
        @if (_isLoading)
        {
            <div style="display:flex;gap:10px;">
                <div style="width:28px;height:28px;border-radius:8px;background:rgba(255,92,0,0.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i data-lucide="bot" style="width:16px;height:16px;color:var(--admin-orange-primary);"></i>
                </div>
                <div style="padding:12px 16px;border-radius:4px 16px 16px 16px;background:var(--admin-bg-elevated);display:flex;gap:4px;">
                    <div style="width:6px;height:6px;border-radius:50%;background:var(--admin-text-tertiary);animation:pulse 1.5s infinite;"></div>
                    <div style="width:6px;height:6px;border-radius:50%;background:var(--admin-text-tertiary);animation:pulse 1.5s infinite 0.3s;"></div>
                    <div style="width:6px;height:6px;border-radius:50%;background:var(--admin-text-tertiary);animation:pulse 1.5s infinite 0.6s;"></div>
                </div>
            </div>
        }
    </div>

    @* Input area *@
    <div style="padding:16px 20px;border-top:1px solid var(--admin-border-subtle);display:flex;gap:10px;">
        <input type="text" @bind="_inputText" @bind:event="oninput" @onkeydown="HandleKeyDown"
               placeholder="Hỏi AI về cửa hàng..."
               style="flex:1;padding:10px 16px;border-radius:12px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:14px;outline:none;"
               disabled="@_isLoading" />
        <button @onclick="SendMessage" disabled="@(_isLoading || string.IsNullOrWhiteSpace(_inputText))"
                style="padding:10px 16px;border-radius:12px;border:none;background:var(--admin-orange-primary);color:#FFF;cursor:pointer;display:flex;align-items:center;gap:6px;font-weight:600;font-size:13px;opacity:@(_isLoading || string.IsNullOrWhiteSpace(_inputText) ? "0.5" : "1");">
            <i data-lucide="send" style="width:16px;height:16px;"></i>
        </button>
    </div>
</div>

<style>
    @@keyframes pulse { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }
</style>

@code {
    [Parameter] public Guid ShopId { get; set; }

    private List<ChatMsg> _messages = new();
    private string _inputText = "";
    private bool _isLoading;

    private record ChatMsg(string Role, string Content, List<string>? ToolsUsed = null);

    private static readonly (string Icon, string Text)[] _suggestions = new[]
    {
        ("package-search", "Kiểm tra tồn kho thấp"),
        ("trending-up", "Sản phẩm bán chạy tuần này"),
        ("chef-hat", "Danh sách công thức"),
        ("calculator", "Phân tích chi phí"),
        ("coffee", "Danh sách menu hiện tại"),
        ("alert-triangle", "Cảnh báo hết hàng")
    };

    private async Task SendMessage()
    {
        if (string.IsNullOrWhiteSpace(_inputText) || _isLoading) return;
        var text = _inputText.Trim();
        _inputText = "";
        _messages.Add(new ChatMsg("user", text));
        _isLoading = true;
        StateHasChanged();

        try
        {
            var request = new PosDataService.AiChatRequestDto(ShopId,
                _messages.Where(m => m.Role == "user" || m.Role == "assistant")
                    .Select(m => new PosDataService.AiChatMessageDto(m.Role, m.Content)).ToList());
            var response = await DataService.SendAiChatAsync(request);
            _messages.Add(new ChatMsg("assistant", response?.Content ?? "Không nhận được phản hồi.", response?.ToolsUsed));
        }
        catch (Exception ex)
        {
            _messages.Add(new ChatMsg("assistant", $"Lỗi: {ex.Message}"));
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private async Task SendSuggestion(string text)
    {
        _inputText = text;
        await SendMessage();
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !e.ShiftKey) await SendMessage();
    }

    private void ClearChat() { _messages.Clear(); StateHasChanged(); }
}
