<?php
use App\Enums\QrCodeType;
use App\Models\QrCode;
use App\Models\QrCodeScan;
use Flux\Flux;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
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">{{ __('QR Codes') }}</flux:heading>
            <flux:subheading size="lg">{{ __('Manage QR codes and review scan analytics') }}</flux:subheading>
        </div>

        <flux:button variant="primary" icon="plus" :href="route('admin.qr-codes.create')" wire:navigate data-test="create-qr-code-button">
            {{ __('New QR Code') }}
        </flux:button>
    </div>

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

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

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

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

    <div class="flex flex-col gap-4 sm:flex-row sm:items-end">
        <flux:input
            wire:model.live.debounce.300ms="search"
            icon="magnifying-glass"
            :label="__('Search')"
            :placeholder="__('Search by name, short code, or target URL')"
            class="sm:max-w-sm"
            data-test="qr-codes-search-input"
        />

        <flux:select wire:model.live="typeFilter" :label="__('Type')" class="sm:max-w-xs" data-test="qr-codes-type-filter">
            <flux:select.option value="all">{{ __('All') }}</flux:select.option>
            @foreach (QrCodeType::cases() as $case)
                <flux:select.option :value="$case->value">{{ $case->label() }}</flux:select.option>
            @endforeach
        </flux:select>

        <flux:select wire:model.live="statusFilter" :label="__('Status')" class="sm:max-w-xs" data-test="qr-codes-status-filter">
            <flux:select.option value="all">{{ __('All') }}</flux:select.option>
            <flux:select.option value="active">{{ __('Active') }}</flux:select.option>
            <flux:select.option value="inactive">{{ __('Inactive') }}</flux:select.option>
        </flux:select>

        <flux:select wire:model.live="perPage" :label="__('Per page')" class="sm:max-w-32" data-test="qr-codes-per-page">
            <flux:select.option value="25">25</flux:select.option>
            <flux:select.option value="50">50</flux:select.option>
            <flux:select.option value="100">100</flux:select.option>
        </flux:select>
    </div>

    <flux:table :paginate="$this->codes">
        <flux:table.columns>
            <flux:table.column>{{ __('') }}</flux:table.column>
            <flux:table.column>{{ __('Name') }}</flux:table.column>
            <flux:table.column>{{ __('Type') }}</flux:table.column>
            <flux:table.column>{{ __('Short Code') }}</flux:table.column>
            <flux:table.column>{{ __('Target') }}</flux:table.column>
            <flux:table.column>{{ __('Scans') }}</flux:table.column>
            <flux:table.column>{{ __('Last Scanned') }}</flux:table.column>
            <flux:table.column>{{ __('Status') }}</flux:table.column>
            <flux:table.column>{{ __('Actions') }}</flux:table.column>
        </flux:table.columns>

        <flux:table.rows>
            @forelse ($this->codes as $qrCode)
                <flux:table.row :key="$qrCode->id" data-test="qr-code-row">
                    <flux:table.cell>
                        <img
                            src="{{ route('admin.qr-codes.preview', $qrCode) }}"
                            alt="{{ __('QR code preview for :name', ['name' => $qrCode->name]) }}"
                            class="size-10 rounded border border-zinc-200 dark:border-zinc-700"
                            loading="lazy"
                        />
                    </flux:table.cell>
                    <flux:table.cell variant="strong">{{ $qrCode->name }}</flux:table.cell>
                    <flux:table.cell>
                        <flux:badge :color="$this->typeBadgeColor($qrCode->type)">{{ $qrCode->type->label() }}</flux:badge>
                        @unless ($qrCode->is_dynamic)
                            <flux:badge color="zinc" size="sm">{{ __('Static') }}</flux:badge>
                        @endunless
                    </flux:table.cell>
                    <flux:table.cell>
                        <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-1"
                        >
                            <flux:text class="max-w-48 truncate font-mono text-xs">{{ $qrCode->publicUrl() }}</flux:text>
                            <button type="button" @click="copy()" class="shrink-0 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>
                    </flux:table.cell>
                    <flux:table.cell>
                        @if ($qrCode->target_url)
                            <flux:link href="{{ $qrCode->target_url }}" target="_blank" rel="noopener noreferrer" class="block max-w-48 truncate">
                                {{ $qrCode->target_url }}
                            </flux:link>
                        @else
                            <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('Encoded directly (not trackable)') }}</flux:text>
                        @endif
                    </flux:table.cell>
                    <flux:table.cell>{{ $qrCode->human_scan_count }}</flux:table.cell>
                    <flux:table.cell>{{ $qrCode->last_scanned_at?->format('d M Y, H:i') ?? '-' }}</flux:table.cell>
                    <flux:table.cell>
                        <flux:badge :color="$qrCode->is_active ? 'green' : 'zinc'">
                            {{ $qrCode->is_active ? __('Active') : __('Inactive') }}
                        </flux:badge>
                    </flux:table.cell>
                    <flux:table.cell>
                        <div class="flex items-center gap-1">
                            <flux:tooltip :content="__('View analytics')">
                                <flux:button size="sm" variant="ghost" icon="eye" :href="route('admin.qr-codes.show', $qrCode)" wire:navigate data-test="view-qr-code-button" />
                            </flux:tooltip>

                            <flux:tooltip :content="__('Download PNG')">
                                <flux:button size="sm" variant="ghost" icon="arrow-down-tray" :href="route('admin.qr-codes.download', [$qrCode, 'png'])" data-test="download-qr-code-button" />
                            </flux:tooltip>

                            <flux:modal.trigger name="toggle-active-{{ $qrCode->id }}">
                                <flux:tooltip :content="$qrCode->is_active ? __('Deactivate') : __('Activate')">
                                    <flux:button size="sm" variant="ghost" icon="power" data-test="toggle-active-qr-code-button" />
                                </flux:tooltip>
                            </flux:modal.trigger>

                            <flux:modal.trigger name="delete-qr-{{ $qrCode->id }}">
                                <flux:tooltip :content="__('Delete')">
                                    <flux:button size="sm" variant="ghost" icon="trash" data-test="delete-qr-code-button" />
                                </flux:tooltip>
                            </flux:modal.trigger>
                        </div>
                    </flux:table.cell>
                </flux:table.row>
            @empty
                <flux:table.row>
                    <flux:table.cell colspan="9" align="center" data-test="qr-codes-empty-state">
                        <div class="flex flex-col items-center gap-3 py-6">
                            <flux:text class="text-zinc-500 dark:text-zinc-400">{{ __('No QR codes found') }}</flux:text>
                            <flux:button variant="primary" icon="plus" :href="route('admin.qr-codes.create')" wire:navigate>
                                {{ __('Create your first QR code') }}
                            </flux:button>
                        </div>
                    </flux:table.cell>
                </flux:table.row>
            @endforelse
        </flux:table.rows>
    </flux:table>

    {{-- Confirmation modals render outside the table markup: a <dialog>/popover
    inside a <tbody> is invalid HTML and gets relocated by the browser's parser. --}}
    @foreach ($this->codes as $qrCode)
        <flux:modal name="toggle-active-{{ $qrCode->id }}" class="max-w-lg">
            <form wire:submit="toggleActive({{ $qrCode->id }})" class="space-y-6">
                <div>
                    <flux:heading size="lg">
                        {{ $qrCode->is_active ? __('Deactivate QR code') : __('Activate QR code') }}
                    </flux:heading>
                    <flux:subheading>
                        @if ($qrCode->is_active)
                            {{ __('The public URL for :name will stop redirecting until you reactivate it.', ['name' => $qrCode->name]) }}
                        @else
                            {{ __('The public URL for :name will start redirecting again.', ['name' => $qrCode->name]) }}
                        @endif
                    </flux:subheading>
                </div>

                <div class="flex justify-end space-x-2 rtl:space-x-reverse">
                    <flux:modal.close>
                        <flux:button variant="filled">{{ __('Cancel') }}</flux:button>
                    </flux:modal.close>

                    <flux:button variant="primary" type="submit" data-test="confirm-toggle-active">
                        {{ $qrCode->is_active ? __('Deactivate') : __('Activate') }}
                    </flux:button>
                </div>
            </form>
        </flux:modal>

        <flux:modal name="delete-qr-{{ $qrCode->id }}" class="max-w-lg">
            <form wire:submit="delete({{ $qrCode->id }})" class="space-y-6">
                <div>
                    <flux:heading size="lg">{{ __('Delete QR code') }}</flux:heading>
                    <flux:subheading>
                        {{ __('Are you sure you want to delete :name?', ['name' => $qrCode->name]) }}
                    </flux:subheading>
                </div>

                <flux:callout
                    variant="warning"
                    icon="exclamation-triangle"
                    :heading="__('Printed copies will stop working')"
                    :text="__('If this code has been printed on flyers, packaging, or signage, those physical copies will point at a dead link once deleted. Consider deactivating it instead if it may still be in circulation.')"
                />

                <div class="flex justify-end space-x-2 rtl:space-x-reverse">
                    <flux:modal.close>
                        <flux:button variant="filled">{{ __('Cancel') }}</flux:button>
                    </flux:modal.close>

                    <flux:button variant="danger" type="submit" data-test="confirm-delete-qr-code">
                        {{ __('Delete') }}
                    </flux:button>
                </div>
            </form>
        </flux:modal>
    @endforeach
</section>