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

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
        @foreach (var st in new[] { ("all", "", "Tất cả"), ("Pending", "clock", "Chờ"), ("InProgress", "flame", "Đang làm"), ("Ready", "check-circle", "Sẵn sàng"), ("Served", "check-check", "Đã phục vụ") })
        {
            <button @onclick='() => LoadKitchenTickets(st.Item1)'
                style="padding:6px 14px;border-radius:6px;border:none;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s;@(_kitchenStatusFilter == st.Item1 ? "background:var(--admin-orange-primary);color:white;" : "background:transparent;color:var(--admin-text-secondary);")">
                @if (!string.IsNullOrEmpty(st.Item2)) { <i data-lucide="@st.Item2" style="width:12px;height:12px;vertical-align:middle;margin-right:2px;"></i> }@st.Item3
            </button>
        }
    </div>
    <div style="display:flex;gap:8px;">
        <span class="admin-status-badge admin-status-badge--setup" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Chờ: @_kitchenTickets.Count(t => t.Status == "Pending")</span>
        <span class="admin-status-badge admin-status-badge--paused" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Đang làm: @_kitchenTickets.Count(t => t.Status == "InProgress")</span>
        <span class="admin-status-badge admin-status-badge--online" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Sẵn sàng: @_kitchenTickets.Count(t => t.Status == "Ready")</span>
    </div>
</div>
@if (!_kitchenTickets.Any())
{
    @RenderEmpty("flame", "#F59E0B", "Không có ticket bếp", "Ticket sẽ xuất hiện khi có đơn từ POS")
}
else
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;">
        @foreach (var ticket in _kitchenTickets)
        {
            var ticketColor = ticket.Status switch { "Pending" => "#F59E0B", "InProgress" => "#3B82F6", "Ready" => "#22C55E", "Served" => "#6B6B6F", _ => "#6B6B6F" };
            var ticketLabel = ticket.Status switch { "Pending" => "Chờ", "InProgress" => "Đang làm", "Ready" => "Sẵn sàng", "Served" => "Đã phục vụ", _ => ticket.Status };
            var elapsed = (DateTime.UtcNow - ticket.CreatedAt).TotalMinutes;
            <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);border-top:4px solid @ticketColor;border-radius:12px;padding:16px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                    <span style="font-weight:700;font-size:13px;font-family:monospace;">P@(ticket.Priority)</span>
                    <span style="font-size:10px;font-weight:700;padding:3px 10px;border-radius:6px;background:@($"{ticketColor}22");color:@ticketColor;">@ticketLabel</span>
                </div>
                <div style="font-size:14px;font-weight:600;margin-bottom:4px;">@ticket.ItemName</div>
                <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:12px;">@(ticket.Station ?? "Bếp chính")</div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding-top:8px;border-top:1px solid var(--admin-border-subtle);">
                    <span style="font-size:11px;color:var(--admin-text-tertiary);"><i data-lucide="clock" style="width:12px;height:12px;vertical-align:middle;"></i> @((int)elapsed) phút</span>
                    <div style="display:flex;gap:4px;">
                        @if (ticket.Status == "Pending")
                        {
                            <button @onclick='() => UpdateTicketStatus(ticket.Id, "inprogress")' style="padding:4px 10px;border-radius:6px;border:none;background:rgba(59,130,246,0.15);color:#3B82F6;font-size:11px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:3px;">
                                <i data-lucide="flame" style="width:11px;height:11px;"></i> Bắt đầu
                            </button>
                        }
                        @if (ticket.Status == "InProgress")
                        {
                            <button @onclick='() => UpdateTicketStatus(ticket.Id, "ready")' style="padding:4px 10px;border-radius:6px;border:none;background:rgba(34,197,94,0.15);color:#22C55E;font-size:11px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:3px;">
                                <i data-lucide="check" style="width:11px;height:11px;"></i> Xong
                            </button>
                        }
                        @if (ticket.Status == "Ready")
                        {
                            <button @onclick='() => UpdateTicketStatus(ticket.Id, "served")' style="padding:4px 10px;border-radius:6px;border:none;background:rgba(107,107,111,0.15);color:#6B6B6F;font-size:11px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:3px;">
                                <i data-lucide="check-check" style="width:11px;height:11px;"></i> Đã phục vụ
                            </button>
                        }
                    </div>
                </div>
            </div>
        }
    </div>
}

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

    // Kitchen state
    private List<PosDataService.KitchenTicketInfo> _kitchenTickets = new();
    private string _kitchenStatusFilter = "all";
    private string? _errorMessage;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
            _kitchenTickets = await DataService.GetKitchenTicketsAsync(ShopId);
    }

    // ═══ KITCHEN ═══
    private async Task LoadKitchenTickets(string status)
    {
        _kitchenStatusFilter = status;
        try
        {
            if (ShopId != Guid.Empty)
            {
                if (status == "all")
                    _kitchenTickets = await DataService.GetKitchenTicketsAsync(ShopId, "");
                else
                    _kitchenTickets = await DataService.GetKitchenTicketsAsync(ShopId, status);
            }
        }
        catch (Exception ex) { _errorMessage = $"Không thể tải kitchen tickets: {ex.Message}"; }
        StateHasChanged();
    }

    private async Task UpdateTicketStatus(Guid ticketId, string newStatus)
    {
        try
        {
            await DataService.UpdateTicketStatusAsync(ticketId, new PosDataService.UpdateTicketStatusRequest(newStatus));
            if (ShopId != Guid.Empty)
            {
                if (_kitchenStatusFilter == "all")
                    _kitchenTickets = await DataService.GetKitchenTicketsAsync(ShopId, "");
                else
                    _kitchenTickets = await DataService.GetKitchenTicketsAsync(ShopId, _kitchenStatusFilter);
            }
        }
        catch (Exception ex) { _errorMessage = $"Không thể cập nhật trạng thái: {ex.Message}"; }
        StateHasChanged();
    }

    private RenderFragment RenderEmpty(string icon, string color, string title, string desc, string? ctaIcon = null, string? ctaLabel = null, string? ctaHref = null) => __builder =>
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">@title</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">@desc</p>
            @if (ctaIcon != null && ctaLabel != null)
            {
                <a href="@(ctaHref ?? $"/admin/shop/{ShopId}/menu")" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                    <i data-lucide="@ctaIcon" style="width:16px;height:16px;"></i>
                    @ctaLabel
                </a>
            }
        </div>
    };

    private static string HexToRgb(string hex)
    {
        hex = hex.TrimStart('#');
        if (hex.Length != 6) return "0,0,0";
        return $"{Convert.ToInt32(hex[..2], 16)},{Convert.ToInt32(hex[2..4], 16)},{Convert.ToInt32(hex[4..], 16)}";
    }
}
