@extends('layouts.app')

@section('title', 'Antrian Distribusi Qurban - Sistem Distribusi Qurban')

@section('header_title', 'Antrian Distribusi')
@section('header_subtitle', 'Scan kupon penerima untuk memasukkannya ke dalam urutan antrean pengambilan daging')

@section('content')
<div style="display: grid; grid-template-columns: 1fr 2fr; gap: 2rem; align-items: start;">
    
    <!-- Left Column: Scan Panel & Manual Add -->
    <div style="display: flex; flex-direction: column; gap: 1.5rem;">
        
        <!-- Live QR Scanner Panel -->
        <div class="panel scan-panel">
            <h2 class="scan-title">📷 Kamera QR Scanner</h2>
            <p class="scan-desc" style="margin-bottom: 1rem;">Arahkan QR Code kupon ke kamera untuk check-in.</p>
            
            <div class="scanner-webcam-container" style="margin: 0 auto; max-width: 100%; border-color: var(--accent);">
                <div id="reader"></div>
            </div>
            
            <div style="margin-top: 1rem; text-align: center;">
                <span id="scanner-status" class="badge badge-success" style="font-size: 0.7rem;">Kamera Aktif</span>
            </div>
        </div>

        <!-- Manual Add Panel -->
        <div class="panel">
            <h2 class="panel-title" style="margin-bottom: 0.75rem;">⌨️ Check-In Manual</h2>
            <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem;">Ketik kupon manual jika QR Code rusak atau tidak terbaca.</p>
            
            <!-- Quick text input -->
            <div class="scan-input-group" style="background: var(--bg-main); border: 1px solid var(--border); margin-bottom: 1rem;">
                <input type="text" id="coupon-search-input" class="scan-input" style="color: var(--text-main); font-weight: 700;" placeholder="Ketik Kode Kupon (e.g. USW-26001)...">
                <button class="btn-scan" id="submit-search-btn" style="background: var(--primary);">Tambah</button>
            </div>

            <div style="display: flex; align-items: center; justify-content: center; gap: 0.5rem; margin: 0.5rem 0;">
                <span style="height: 1px; background: var(--border); flex-grow: 1;"></span>
                <span style="font-size: 0.75rem; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Atau</span>
                <span style="height: 1px; background: var(--border); flex-grow: 1;"></span>
            </div>

            <!-- Dropdown selector search -->
            <form id="manual-dropdown-form" style="margin-top: 0.5rem;">
                <label for="select-participant" class="login-form-label" style="font-size: 0.8rem; text-transform: uppercase; color: var(--primary-dark);">Pilih Nama Penerima:</label>
                <div style="display: flex; gap: 0.5rem; margin-top: 0.35rem;">
                    <select id="select-participant" class="form-control" style="flex-grow: 1;" required>
                        <option value="">-- Cari Nama / Kupon --</option>
                        @foreach($allParticipants as $p)
                            <option value="{{ $p->no_kupon }}">{{ $p->no_kupon }} - {{ $p->nama }}</option>
                        @endforeach
                    </select>
                    <button type="button" id="btn-add-dropdown" class="btn btn-secondary" style="padding: 0.5rem 1rem;">
                        Antrikan
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Right Column: Live Queue List -->
    <div class="panel" style="min-height: 500px;">
        <div class="panel-header">
            <h2 class="panel-title"><span>📋</span> Antrean Ambil Daging ({{ $queue->count() }} orang)</h2>
            <button onclick="window.location.reload()" class="btn btn-secondary btn-sm">🔄 Refresh List</button>
        </div>

        @if($queue->isEmpty())
            <div style="text-align: center; padding: 5rem 0; color: var(--text-muted); display: flex; flex-direction: column; align-items: center; justify-content: center; flex-grow: 1;">
                <span style="font-size: 4rem; margin-bottom: 1.5rem; animation: pulse 2s infinite;">⏳</span>
                <strong style="font-size: 1.15rem; color: var(--primary-dark);">Belum Ada Antrean</strong>
                <p style="font-size: 0.85rem; margin-top: 0.5rem; max-width: 300px;">Scan QR Code kupon peserta di sebelah kiri untuk memasukkannya ke dalam urutan antrean.</p>
            </div>
        @else
            <div class="table-wrapper">
                <table class="table-custom">
                    <thead>
                        <tr>
                            <th style="width: 8%; text-align: center;">No</th>
                            <th style="width: 25%;">Penerima (Kupon)</th>
                            <th style="width: 12%;">Tipe</th>
                            <th style="width: 20%;">Jatah Daging</th>
                            <th style="width: 20%;">Bawa Titipan</th>
                            <th style="width: 15%; text-align: center;">Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($queue as $index => $item)
                            @php
                                $p = $item->participant;
                                $alloc = $p->getAllocation();
                                $ownStatus = $p->distribution ? $p->distribution->status : 'Belum';
                                $pendingTitips = $p->entrustedToMe->where('status', '!=', 'Selesai');
                                $hasTitipans = $pendingTitips->count() > 0;
                            @endphp
                            <tr>
                                <!-- Queue number -->
                                <td style="text-align: center; font-weight: 800; font-size: 1.15rem; color: var(--primary-dark); vertical-align: middle;">
                                    <span style="display: inline-flex; width: 28px; height: 28px; border-radius: 50%; background: var(--primary-light); align-items: center; justify-content: center;">
                                        {{ $index + 1 }}
                                    </span>
                                </td>

                                <!-- Participant details -->
                                <td>
                                    <strong style="font-size: 0.95rem; color: var(--text-main); display: block;">{{ $p->nama }}</strong>
                                    <span style="font-size: 0.75rem; color: var(--accent); font-weight: 700;">Kupon: {{ $p->no_kupon }}</span>
                                </td>

                                <!-- Type -->
                                <td style="vertical-align: middle;">
                                    <span style="font-size: 0.8rem; background: var(--primary-light); color: var(--primary-dark); padding: 0.25rem 0.5rem; border-radius: 4px; font-weight: 700;">
                                        {{ $p->jenis }}
                                    </span>
                                </td>

                                <!-- Jatah Daging -->
                                <td>
                                    <div style="font-size: 0.8rem; line-height: 1.3;">
                                        @if($alloc->daging_sapi > 0) 🐮 S: {{ $alloc->daging_sapi }} @endif
                                        @if($alloc->daging_kambing > 0) 🐐 K: {{ $alloc->daging_kambing }} @endif
                                        @if($alloc->hak_2kg > 0) ⭐ 2K: {{ $alloc->hak_2kg }} @endif
                                        @if($alloc->hak_paha > 0) 🍗 Paha @endif
                                        
                                        @if($ownStatus === 'Titip')
                                            <div style="font-size: 0.75rem; color: var(--info); font-weight: 700; margin-top: 0.15rem;">
                                                ⚠️ Dititip ke {{ $p->distribution->entrustee->nama ?? '-' }}
                                            </div>
                                        @endif
                                    </div>
                                </td>

                                <!-- Entrusted Packages Tally -->
                                <td>
                                    @if(!$hasTitipans)
                                        <span style="font-size: 0.75rem; color: var(--text-muted); font-style: italic;">Tidak ada</span>
                                    @else
                                        @php
                                            $tally = [];
                                            foreach ($pendingTitips as $t) {
                                                $tally[$t->participant->jenis] = ($tally[$t->participant->jenis] ?? 0) + 1;
                                            }
                                            $tallyStrings = [];
                                            foreach ($tally as $type => $count) {
                                                $tallyStrings[] = "{$count}x {$type}";
                                            }
                                        @endphp
                                        <div style="display: flex; flex-direction: column; gap: 0.15rem;">
                                            <span style="font-size: 0.75rem; font-weight: 700; color: var(--info);">
                                                📋 {{ $pendingTitips->count() }} Paket Titipan:
                                            </span>
                                            <span style="font-size: 0.75rem; font-weight: 600; color: var(--text-muted);">
                                                {{ implode(', ', $tallyStrings) }}
                                            </span>
                                        </div>
                                    @endif
                                </td>

                                <!-- Actions -->
                                <td style="text-align: center; vertical-align: middle;">
                                    <div style="display: flex; flex-direction: column; gap: 0.35rem; align-items: stretch;">
                                        @if($hasTitipans)
                                            <!-- Group representative release -->
                                            <form action="{{ route('distribution.distribute-all', $p->id) }}" method="POST" style="display: block;">
                                                @csrf
                                                <button type="submit" class="btn btn-primary btn-sm" style="width: 100%; justify-content: center; font-size: 0.75rem; padding: 0.4rem;">
                                                    🎁 Serahkan Semua
                                                </button>
                                            </form>
                                        @else
                                            <!-- Simple release -->
                                            <form action="{{ route('distribution.distribute', $p->id) }}" method="POST" style="display: block;">
                                                @csrf
                                                <button type="submit" class="btn btn-primary btn-sm" style="width: 100%; justify-content: center; font-size: 0.75rem; padding: 0.4rem;">
                                                    ✅ Serahkan
                                                </button>
                                            </form>
                                        @endif

                                        <!-- Cancel/Remove from Queue -->
                                        <form action="{{ route('distribution.cancel-queue', $p->id) }}" method="POST" style="display: block;">
                                            @csrf
                                            <button type="submit" class="btn btn-danger btn-sm" style="width: 100%; justify-content: center; padding: 0.25rem; font-size: 0.7rem;" onclick="return confirm('Keluarkan dari antrean?')">
                                                ❌ Batal
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</div>

<!-- Audio validation effect -->
<audio id="beep-sound" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-600.wav" preload="auto"></audio>
@endsection

@section('scripts')
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>

<script>
    let html5QrcodeScanner = null;
    let isScanningPaused = false;
    const searchInput = document.getElementById('coupon-search-input');
    const submitBtn = document.getElementById('submit-search-btn');
    const beepSound = document.getElementById('beep-sound');
    
    // Dropdown elements
    const dropdownSelect = document.getElementById('select-participant');
    const dropdownAddBtn = document.getElementById('btn-add-dropdown');

    // Trigger QR scanner on page load
    document.addEventListener('DOMContentLoaded', () => {
        startScanner();
    });

    // Handle manual text input check-in
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            triggerCheckIn(searchInput.value.trim());
        }
    });
    submitBtn.addEventListener('click', () => {
        triggerCheckIn(searchInput.value.trim());
    });

    // Handle manual dropdown check-in
    dropdownAddBtn.addEventListener('click', () => {
        const val = dropdownSelect.value;
        if (!val) {
            alert('Pilih peserta terlebih dahulu.');
            return;
        }
        triggerCheckIn(val);
    });

    function triggerCheckIn(couponCode) {
        if (!couponCode) return;

        fetch(`{{ route('distribution.search-ajax') }}?code=${encodeURIComponent(couponCode)}`)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Play sound
                    try {
                        beepSound.play().catch(e => console.log('Audio autoplay blocked'));
                    } catch(e) {}

                    if (navigator.vibrate) {
                        navigator.vibrate(100);
                    }

                    // Show success toast & refresh page to show in list
                    showTempToast(data.message, 'success');
                    
                    setTimeout(() => {
                        window.location.reload();
                    }, 1200);
                } else {
                    showTempToast(data.message, 'error');
                    resumeScannerAfterDelay();
                }
            })
            .catch(err => {
                showTempToast('Gagal memproses kupon. Silakan coba lagi.', 'error');
                resumeScannerAfterDelay();
            });

        // Reset input fields
        searchInput.value = '';
        dropdownSelect.value = '';
    }

    function resumeScannerAfterDelay() {
        setTimeout(() => {
            isScanningPaused = false;
            try {
                if (html5QrcodeScanner) {
                    html5QrcodeScanner.resume();
                }
            } catch (e) {
                console.log("Scanner resume failed", e);
            }
        }, 3000); // 3 seconds cooldown
    }

    function showTempToast(message, type) {
        const container = document.querySelector('.toast-container');
        if (!container) return;

        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.innerHTML = `
            <span class="toast-icon">${type === 'success' ? '✅' : '⚠️'}</span>
            <div class="toast-content">
                <span class="toast-message">${message}</span>
            </div>
        `;
        
        container.appendChild(toast);

        setTimeout(() => {
            toast.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-20px)';
            setTimeout(() => toast.remove(), 500);
        }, 3000);
    }

    function startScanner() {
        // Automatically find camera and start scan
        html5QrcodeScanner = new Html5QrcodeScanner(
            "reader", 
            { 
                fps: 15, 
                qrbox: { width: 220, height: 220 },
                aspectRatio: 1.333334
            }, 
            false
        );
        
        html5QrcodeScanner.render((decodedText, decodedResult) => {
            if (isScanningPaused) return;

            const code = decodedText.trim();
            
            // Client-side validation: must match [A-Z]{3}-\d{5} (e.g. USW-26001)
            if (!/^[A-Z]{3}-\d{5}$/i.test(code)) {
                return; // Ignore false positives or invalid QR codes
            }

            // Pause scanning immediately to prevent continuous reading
            isScanningPaused = true;
            try {
                html5QrcodeScanner.pause(true);
            } catch (e) {
                console.log("Scanner pause failed", e);
            }

            triggerCheckIn(code);
        }, (errorMessage) => {
            // Quiet mode on scan failures (which happen continuously during frames checking)
        });
    }
</script>

<style>
    @keyframes pulse {
        0% { transform: scale(1); opacity: 0.7; }
        50% { transform: scale(1.15); opacity: 1; }
        100% { transform: scale(1); opacity: 0.7; }
    }
</style>
@endsection
