<?php
use App\Models\QrCode;
use App\Models\QrCodeScan;
use Flux\Flux;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
?>

<section class="w-full space-y-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <flux:heading size="xl" level="1">{{ $qrCode->name }}</flux:heading>
            <flux:subheading size="lg">
                <flux:badge :color="$qrCode->is_active ? 'green' : 'zinc'">
                    {{ $qrCode->is_active ? __('Active') : __('Inactive') }}
                </flux:badge>
                <flux:badge color="zinc">{{ $qrCode->type->label() }}</flux:badge>
            </flux:subheading>
        </div>

        <flux:button variant="ghost" icon="arrow-left" :href="route('admin.qr-codes')" wire:navigate>
            {{ __('Back to QR codes') }}
        </flux:button>
    </div>

    <flux:card>
        <div class="flex flex-col gap-6 sm:flex-row sm:items-start sm:justify-between">
            <div class="flex gap-4">
                <img
                    src="{{ route('admin.qr-codes.preview', $qrCode) }}"
                    alt="{{ __('QR code for :name', ['name' => $qrCode->name]) }}"
                    class="size-32 rounded border border-zinc-200 dark:border-zinc-700"
                />

                <div class="space-y-3">
                    <div>
                        <flux:text class="text-sm text-zinc-500 dark:text-zinc-400">{{ __('Public URL') }}</flux:text>
                        <div
                            x-data="{
                                copied: false,
                                async copy() {
                                    try {
                                        await navigator.clipboard.writeText('{{ $qrCode->publicUrl() }}');
                                        this.copied = true;
                                        setTimeout(() => this.copied = false, 1500);
                                    } catch (e) {
                                        console.warn('Could not copy to clipboard');
                                    }
                                }
                            }"
                            class="flex items-center gap-2"
                        >
                            <flux:link href="{{ $qrCode->publicUrl() }}" target="_blank" rel="noopener noreferrer" class="font-mono text-sm">
                                {{ $qrCode->publicUrl() }}
                            </flux:link>
                            <button type="button" @click="copy()" class="cursor-pointer text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200" data-test="copy-public-url">
                                <flux:icon.document-duplicate x-show="!copied" variant="micro" />
                                <flux:icon.check x-show="copied" variant="micro" class="text-green-500" />
                            </button>
                        </div>
                    </div>

                    <flux:switch :checked="$qrCode->is_active" wire:click="toggleActive" :label="$qrCode->is_active ? __('Active') : __('Inactive')" data-test="qr-active-toggle" />

                    <div class="flex gap-2">
                        <flux:button size="sm" icon="arrow-down-tray" :href="route('admin.qr-codes.download', [$qrCode, 'png'])" data-test="download-png-button">
                            {{ __('Download PNG') }}
                        </flux:button>
                        <flux:button size="sm" icon="arrow-down-tray" :href="route('admin.qr-codes.download', [$qrCode, 'svg'])" data-test="download-svg-button">
                            {{ __('Download SVG') }}
                        </flux:button>
                    </div>
                </div>
            </div>
        </div>
    </flux:card>

    <div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <flux:select wire:model.live="range" :label="__('Date range')" class="sm:max-w-xs" data-test="qr-range-filter">
            <flux:select.option value="7">{{ __('Last 7 days') }}</flux:select.option>
            <flux:select.option value="30">{{ __('Last 30 days') }}</flux:select.option>
            <flux:select.option value="90">{{ __('Last 90 days') }}</flux:select.option>
            <flux:select.option value="all">{{ __('All time') }}</flux:select.option>
        </flux:select>

        <div class="space-y-1">
            <flux:switch wire:model.live="humansOnly" :label="__('Humans only')" data-test="qr-humans-only-toggle" />
            <flux:text class="text-sm text-zinc-500 dark:text-zinc-400">
                {{ __('Link-preview crawlers (WhatsApp, Slack, Facebook) hit the redirect too and would otherwise inflate scan counts.') }}
                {{ trans_choice(':count bot scan in this range|:count bot scans in this range', $this->botScanCount, ['count' => $this->botScanCount]) }}
            </flux:text>
        </div>
    </div>

    <div class="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <flux:card size="sm" data-test="stat-total-scans">
            <flux:subheading>{{ __('Total Scans') }}</flux:subheading>
            <flux:heading size="xl">{{ $this->stats['total'] }}</flux:heading>
        </flux:card>

        <flux:card size="sm" data-test="stat-unique-visitors">
            <flux:subheading>{{ __('Unique Visitors') }}</flux:subheading>
            <flux:heading size="xl">{{ $this->stats['unique_visitors'] }}</flux:heading>
        </flux:card>

        <flux:card size="sm" data-test="stat-scans-today">
            <flux:subheading>{{ __('Scans Today') }}</flux:subheading>
            <flux:heading size="xl">{{ $this->stats['today'] }}</flux:heading>
        </flux:card>

        <flux:card size="sm" data-test="stat-times-generated">
            <flux:subheading>{{ __('Times Generated') }}</flux:subheading>
            <flux:heading size="xl">{{ $this->stats['times_generated'] }}</flux:heading>
        </flux:card>
    </div>

    @if ($this->stats['total'] === 0)
        <flux:card>
            <div class="flex flex-col items-center gap-2 py-10 text-center">
                <flux:icon.qr-code class="size-10 text-zinc-400" />
                <flux:heading>{{ __('No scans yet') }}</flux:heading>
                <flux:text class="text-zinc-500 dark:text-zinc-400">
                    {{ __('Once this code is scanned, device, location, and referrer breakdowns will appear here.') }}
                </flux:text>
            </div>
        </flux:card>
    @else
        @if ($this->pendingEnrichmentCount > 0)
            <flux:callout
                variant="secondary"
                icon="information-circle"
                :heading="__(':count scans pending enrichment', ['count' => $this->pendingEnrichmentCount])"
                :text="__('Device, browser, and location details are added by a background job shortly after each scan. These scans are excluded from the breakdowns below until that runs.')"
            />
        @endif

        <flux:card>
            <flux:heading>{{ __('Scans over time') }}</flux:heading>

            <div class="mt-4 space-y-2">
                @php $maxDay = $this->scansByDay->max('total') ?: 1; @endphp
                @forelse ($this->scansByDay as $row)
                    <div class="space-y-1">
                        <div class="flex items-center justify-between text-sm">
                            <span>{{ Carbon::parse($row->day)->format('d M Y') }}</span>
                            <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }}</span>
                        </div>
                        <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                            <div class="h-2 rounded-full bg-blue-500" style="width: {{ round($row->total / $maxDay * 100) }}%"></div>
                        </div>
                    </div>
                @empty
                    <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No scans in this range') }}</flux:text>
                @endforelse
            </div>
        </flux:card>

        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <flux:card data-test="breakdown-device-type">
                <flux:heading>{{ __('Device type') }}</flux:heading>
                <div class="mt-4 space-y-3">
                    @forelse ($this->byDeviceType as $row)
                        @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                        <div class="space-y-1">
                            <div class="flex items-center justify-between text-sm">
                                <span>{{ $row->device_type ?? __('Unknown') }}</span>
                                <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                                <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                            </div>
                        </div>
                    @empty
                        <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No data yet') }}</flux:text>
                    @endforelse
                </div>
            </flux:card>

            <flux:card data-test="breakdown-browser">
                <flux:heading>{{ __('Browser') }}</flux:heading>
                <div class="mt-4 space-y-3">
                    @forelse ($this->byBrowser as $row)
                        @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                        <div class="space-y-1">
                            <div class="flex items-center justify-between text-sm">
                                <span>{{ $row->browser ?? __('Unknown') }}</span>
                                <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                                <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                            </div>
                        </div>
                    @empty
                        <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No data yet') }}</flux:text>
                    @endforelse
                </div>
            </flux:card>

            <flux:card data-test="breakdown-platform">
                <flux:heading>{{ __('Platform') }}</flux:heading>
                <div class="mt-4 space-y-3">
                    @forelse ($this->byPlatform as $row)
                        @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                        <div class="space-y-1">
                            <div class="flex items-center justify-between text-sm">
                                <span>{{ $row->platform ?? __('Unknown') }}</span>
                                <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                                <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                            </div>
                        </div>
                    @empty
                        <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No data yet') }}</flux:text>
                    @endforelse
                </div>
            </flux:card>
        </div>

        <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <flux:card data-test="breakdown-country">
                <flux:heading>{{ __('Country') }}</flux:heading>
                <flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                    {{ __('Scans from local or private IP addresses (e.g. development or office networks) can\'t be geolocated and show as "Unknown".') }}
                </flux:text>
                <div class="mt-4 space-y-3">
                    @forelse ($this->byCountry as $row)
                        @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                        <div class="space-y-1">
                            <div class="flex items-center justify-between text-sm">
                                <span>{{ $row->country ?? __('Unknown') }}</span>
                                <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                                <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                            </div>
                        </div>
                    @empty
                        <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No data yet') }}</flux:text>
                    @endforelse
                </div>
            </flux:card>

            <flux:card data-test="breakdown-city">
                <flux:heading>{{ __('City') }}</flux:heading>
                <div class="mt-4 space-y-3">
                    @forelse ($this->byCity as $row)
                        @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                        <div class="space-y-1">
                            <div class="flex items-center justify-between text-sm">
                                <span>{{ $row->city ?? __('Unknown') }}</span>
                                <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                                <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                            </div>
                        </div>
                    @empty
                        <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No data yet') }}</flux:text>
                    @endforelse
                </div>
            </flux:card>
        </div>

        <flux:card data-test="breakdown-referrers">
            <flux:heading>{{ __('Top referrers') }}</flux:heading>
            <flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                {{ __(':count direct scans (opened straight from a camera app, no referrer)', ['count' => $this->directScanCount]) }}
            </flux:text>
            <div class="mt-4 space-y-3">
                @forelse ($this->topReferrers as $row)
                    @php $pct = $this->stats['total'] > 0 ? round($row->total / $this->stats['total'] * 100) : 0; @endphp
                    <div class="space-y-1">
                        <div class="flex items-center justify-between text-sm">
                            <span class="truncate">{{ $row->referer }}</span>
                            <span class="text-zinc-500 dark:text-zinc-400">{{ $row->total }} ({{ $pct }}%)</span>
                        </div>
                        <div class="h-2 w-full rounded-full bg-zinc-100 dark:bg-zinc-700">
                            <div class="h-2 rounded-full bg-blue-500" style="width: {{ $pct }}%"></div>
                        </div>
                    </div>
                @empty
                    <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No referrers recorded') }}</flux:text>
                @endforelse
            </div>
        </flux:card>

        <flux:card>
            <flux:heading>{{ __('Recent scans') }}</flux:heading>

            <flux:table class="mt-4" :paginate="$this->recentScans">
                <flux:table.columns>
                    <flux:table.column>{{ __('Time') }}</flux:table.column>
                    <flux:table.column>{{ __('Device') }}</flux:table.column>
                    <flux:table.column>{{ __('Browser') }}</flux:table.column>
                    <flux:table.column>{{ __('Platform') }}</flux:table.column>
                    <flux:table.column>{{ __('Location') }}</flux:table.column>
                    <flux:table.column>{{ __('IP') }}</flux:table.column>
                    <flux:table.column>{{ __('Bot') }}</flux:table.column>
                </flux:table.columns>

                <flux:table.rows>
                    @forelse ($this->recentScans as $scan)
                        <flux:table.row :key="$scan->id" data-test="recent-scan-row">
                            <flux:table.cell>{{ $scan->scanned_at->format('d M Y, H:i') }}</flux:table.cell>
                            <flux:table.cell>{{ $this->pendingOrValue($scan->enriched_at, $scan->device_type) }}</flux:table.cell>
                            <flux:table.cell>{{ $this->pendingOrValue($scan->enriched_at, $scan->browser) }}</flux:table.cell>
                            <flux:table.cell>{{ $this->pendingOrValue($scan->enriched_at, $scan->platform) }}</flux:table.cell>
                            <flux:table.cell>
                                {{ $this->pendingOrValue($scan->enriched_at, collect([$scan->city, $scan->country])->filter()->implode(', ') ?: null) }}
                            </flux:table.cell>
                            <flux:table.cell>{{ $scan->ip_address ?? '-' }}</flux:table.cell>
                            <flux:table.cell>
                                <flux:badge :color="$scan->is_bot ? 'amber' : 'zinc'">
                                    {{ $scan->is_bot ? __('Bot') : __('Human') }}
                                </flux:badge>
                            </flux:table.cell>
                        </flux:table.row>
                    @empty
                        <flux:table.row>
                            <flux:table.cell colspan="7" align="center">{{ __('No scans in this range') }}</flux:table.cell>
                        </flux:table.row>
                    @endforelse
                </flux:table.rows>
            </flux:table>
        </flux:card>
    @endif
</section>