@page "/admin/shop/{ShopId:guid}/qr-codes"
@layout WebClientTpos.Client.Layout.AdminLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject NavigationManager Nav
@inject IJSRuntime JS

<div class="admin-page-header" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;">
    <div>
        <h1 style="font-size:22px;font-weight:700;margin:0;color:var(--admin-text-primary);">
            <i data-lucide="qr-code" style="width:22px;height:22px;vertical-align:middle;margin-right:8px;color:var(--admin-orange-primary);"></i>Mã QR Thực Đơn
        </h1>
        <p style="font-size:13px;color:var(--admin-text-tertiary);margin:4px 0 0;">Tạo và in mã QR cho từng bàn/phòng để khách hàng quét xem menu</p>
    </div>
    <div style="display:flex;gap:8px;">
        <a href="/admin/shop/@ShopId/tables" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);text-decoration:none;font-size:13px;font-weight:600;">
            <i data-lucide="arrow-left" style="width:14px;height:14px;"></i>Quản lý bàn
        </a>
        @if (_tables.Any())
        {
            <button class="admin-btn-primary" @onclick="BatchGenerateQr" disabled="@_batchGenerating" style="display:inline-flex;align-items:center;gap:6px;">
                <i data-lucide="zap" style="width:14px;height:14px;"></i>@(_batchGenerating ? "Đang tạo..." : "Tạo QR tất cả")
            </button>
            <button class="admin-btn-primary" @onclick="PrintAllQr" style="display:inline-flex;align-items:center;gap:6px;background:#8B5CF6;">
                <i data-lucide="printer" style="width:14px;height:14px;"></i>In mã QR
            </button>
        }
    </div>
</div>

@if (_loading)
{
    <div style="text-align:center;padding:60px;">
        <div style="width:40px;height:40px;border:3px solid var(--admin-border-subtle);border-top-color:var(--admin-orange-primary);border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 12px;"></div>
        <p style="color:var(--admin-text-tertiary);font-size:14px;">Đang tải danh sách bàn...</p>
    </div>
}
else if (!_tables.Any())
{
    <div style="text-align:center;padding:80px 20px;">
        <div style="width:80px;height:80px;border-radius:24px;background:rgba(245,158,11,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
            <i data-lucide="grid-3x3" style="width:36px;height:36px;color:var(--admin-orange-primary);"></i>
        </div>
        <h2 style="font-size:20px;font-weight:700;color:var(--admin-text-primary);margin:0 0 8px;">Chưa có bàn nào</h2>
        <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Tạo bàn trước rồi quay lại đây để tạo mã QR</p>
        <a href="/admin/shop/@ShopId/tables" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
            <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm bàn
        </a>
    </div>
}
else
{
    @* ═══ STATS ═══ *@
    <div style="display:flex;gap:16px;margin-bottom:20px;">
        <div style="padding:12px 20px;border-radius:10px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);">
            <span style="font-size:13px;color:var(--admin-text-tertiary);">Tổng bàn: </span>
            <span style="font-size:15px;font-weight:700;color:var(--admin-text-primary);">@_tables.Count</span>
        </div>
        <div style="padding:12px 20px;border-radius:10px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);">
            <span style="font-size:13px;color:var(--admin-text-tertiary);">Có QR: </span>
            <span style="font-size:15px;font-weight:700;color:#22C55E;">@_tables.Count(t => !string.IsNullOrEmpty(t.QrToken))</span>
        </div>
        <div style="padding:12px 20px;border-radius:10px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);">
            <span style="font-size:13px;color:var(--admin-text-tertiary);">Chưa có QR: </span>
            <span style="font-size:15px;font-weight:700;color:#F59E0B;">@_tables.Count(t => string.IsNullOrEmpty(t.QrToken))</span>
        </div>
    </div>

    @if (!string.IsNullOrEmpty(_batchMessage))
    {
        <div style="margin-bottom:16px;padding:12px 16px;border-radius:10px;background:@(_batchSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");border:1px solid @(_batchSuccess ? "rgba(34,197,94,0.3)" : "rgba(239,68,68,0.3)");font-size:13px;color:@(_batchSuccess ? "#22C55E" : "#EF4444");">
            @_batchMessage
        </div>
    }

    @* ═══ QR CARDS GRID ═══ *@
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:20px;">
        @foreach (var table in _tables)
        {
            var hasQr = !string.IsNullOrEmpty(table.QrToken);
            var menuUrl = $"{Nav.BaseUri}menu/{ShopId}/{table.Id}";
            var qrUrl = hasQr ? $"{Nav.BaseUri}table/{table.QrToken}" : null;
            var displayUrl = qrUrl ?? menuUrl;

            <div style="background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);border-radius:16px;overflow:hidden;">
                @* Table header *@
                <div style="padding:16px 16px 12px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--admin-border-subtle);">
                    <div>
                        <div style="font-size:16px;font-weight:700;color:var(--admin-text-primary);">Bàn @table.TableNumber</div>
                        <div style="font-size:12px;color:var(--admin-text-tertiary);">@(table.Zone ?? "Chung") • @table.Capacity chỗ</div>
                    </div>
                    @if (hasQr)
                    {
                        <span style="font-size:11px;font-weight:600;color:#22C55E;background:rgba(34,197,94,0.1);padding:4px 10px;border-radius:6px;">
                            <span style="width:6px;height:6px;border-radius:50%;background:#22C55E;display:inline-block;margin-right:4px;"></span>Có QR
                        </span>
                    }
                    else
                    {
                        <span style="font-size:11px;font-weight:600;color:#F59E0B;background:rgba(245,158,11,0.1);padding:4px 10px;border-radius:6px;">Chưa có QR</span>
                    }
                </div>

                @* QR Code *@
                <div style="padding:20px;text-align:center;">
                    @if (hasQr)
                    {
                        <div style="background:white;border-radius:12px;padding:16px;display:inline-block;margin-bottom:12px;">
                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=@(Uri.EscapeDataString(displayUrl))" alt="QR Code" style="width:180px;height:180px;" />
                        </div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);word-break:break-all;padding:0 8px;margin-bottom:12px;">@displayUrl</div>
                        <div style="display:flex;gap:8px;justify-content:center;">
                            <button @onclick='() => CopyUrl(displayUrl)' style="padding:6px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;font-size:12px;font-weight:600;display:flex;align-items:center;gap:4px;">
                                <i data-lucide="copy" style="width:12px;height:12px;"></i>Sao chép
                            </button>
                            <button @onclick='() => DownloadQr(table.TableNumber, displayUrl)' style="padding:6px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;font-size:12px;font-weight:600;display:flex;align-items:center;gap:4px;">
                                <i data-lucide="download" style="width:12px;height:12px;"></i>Tải về
                            </button>
                        </div>
                    }
                    else
                    {
                        <div style="padding:20px;color:var(--admin-text-tertiary);">
                            <i data-lucide="qr-code" style="width:48px;height:48px;opacity:0.3;margin-bottom:8px;"></i>
                            <p style="font-size:13px;margin:0 0 12px;">Chưa có mã QR</p>
                            <button class="admin-btn-primary" @onclick="() => GenerateSingleQr(table)" style="font-size:12px;padding:6px 16px;">
                                <i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Tạo QR
                            </button>
                        </div>
                    }
                </div>
            </div>
        }
    </div>
}

@if (_copied)
{
    <div style="position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#059669;color:white;padding:10px 24px;border-radius:10px;font-size:13px;font-weight:600;z-index:300;box-shadow:0 4px 12px rgba(0,0,0,0.15);">
        Đã sao chép URL!
    </div>
}

<style>
    @@keyframes spin { to { transform: rotate(360deg); } }
</style>

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

    private List<PosDataService.TableInfo> _tables = new();
    private bool _loading = true;
    private bool _batchGenerating;
    private string? _batchMessage;
    private bool _batchSuccess;
    private bool _copied;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
            _tables = await DataService.GetTablesAsync(ShopId);
        _loading = false;
    }

    private async Task GenerateSingleQr(PosDataService.TableInfo table)
    {
        try
        {
            var token = await DataService.GenerateTableQrTokenAsync(table.Id);
            if (token != null)
            {
                _tables = await DataService.GetTablesAsync(ShopId);
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"QR generation failed for table {table.TableNumber}: {ex.Message}");
        }
    }

    private async Task BatchGenerateQr()
    {
        _batchGenerating = true;
        _batchMessage = null;
        var generated = 0;
        var failed = 0;

        foreach (var table in _tables.Where(t => string.IsNullOrEmpty(t.QrToken)))
        {
            try
            {
                var token = await DataService.GenerateTableQrTokenAsync(table.Id);
                if (token != null) generated++;
                else failed++;
            }
            catch { failed++; }
        }

        _tables = await DataService.GetTablesAsync(ShopId);

        if (failed == 0)
        {
            _batchMessage = $"Đã tạo mã QR cho {generated} bàn thành công!";
            _batchSuccess = true;
        }
        else
        {
            _batchMessage = $"Tạo xong: {generated} thành công, {failed} thất bại.";
            _batchSuccess = false;
        }
        _batchGenerating = false;
    }

    private async Task CopyUrl(string url)
    {
        try
        {
            await JS.InvokeVoidAsync("navigator.clipboard.writeText", url);
            _copied = true;
            StateHasChanged();
            await Task.Delay(2000);
            _copied = false;
            StateHasChanged();
        }
        catch { }
    }

    private async Task DownloadQr(string tableNumber, string url)
    {
        try
        {
            var qrImageUrl = $"https://api.qrserver.com/v1/create-qr-code/?size=400x400&format=png&data={Uri.EscapeDataString(url)}";
            await JS.InvokeVoidAsync("eval",
                $"var a=document.createElement('a');a.href='{qrImageUrl}';a.download='qr-ban-{tableNumber}.png';a.target='_blank';document.body.appendChild(a);a.click();document.body.removeChild(a);");
        }
        catch { }
    }

    private async Task PrintAllQr()
    {
        var tablesWithQr = _tables.Where(t => !string.IsNullOrEmpty(t.QrToken)).ToList();
        if (!tablesWithQr.Any()) return;

        var cards = string.Join("", tablesWithQr.Select(t =>
        {
            var qrUrl = $"{Nav.BaseUri}table/{t.QrToken}";
            return $@"
                <div style=""width:280px;padding:24px;border:1px solid #E5E7EB;border-radius:12px;text-align:center;page-break-inside:avoid;"">
                    <h3 style=""font-size:18px;font-weight:700;margin:0 0 4px;"">Ban {t.TableNumber}</h3>
                    <p style=""font-size:12px;color:#6B7280;margin:0 0 12px;"">{t.Zone ?? "Chung"} - {t.Capacity} cho</p>
                    <img src=""https://api.qrserver.com/v1/create-qr-code/?size=240x240&data={Uri.EscapeDataString(qrUrl)}"" style=""width:200px;height:200px;"" />
                    <p style=""font-size:10px;color:#9CA3AF;margin:8px 0 0;word-break:break-all;"">{qrUrl}</p>
                </div>";
        }));

        var html = $@"
            <html>
            <head><title>Ma QR - Cua hang</title></head>
            <body style=""font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:20px;"">
                <h1 style=""text-align:center;font-size:22px;margin-bottom:24px;"">Ma QR Thuc Don</h1>
                <div style=""display:flex;flex-wrap:wrap;gap:16px;justify-content:center;"">
                    {cards}
                </div>
            </body>
            </html>";

        await JS.InvokeVoidAsync("eval",
            $"var w=window.open('','_blank','width=900,height=700');w.document.write(`{html.Replace("`", "\\`")}`);w.document.close();setTimeout(function(){{w.print();}},500);");
    }
}
