<div x-data="{ showErrorModal: {{ session()->has('error') ? 'true' : 'false' }} }"
     x-init="if (showErrorModal) { $nextTick(() => { $dispatch('open-modal', 'error-modal') }) }">
<form id="verification-form"
      action="{{ route('verify') }}"
      method="GET"
      class="space-y-6 max-w-2xl mx-auto">

    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
        <h3 class="text-lg font-semibold text-blue-800 mb-2">How to verify a product:</h3>
        <ul class="text-blue-700 list-disc list-inside space-y-1">
            <li>Enter either the Serial Number or the IMEI number of your product.</li>
            <li>Click the "Verify Product" button</li>
            <li>View the product authentication results</li>
        </ul>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-1 gap-6">
        <!-- Serial Number Input -->
        <div>
            <label for="serial_no" class="block text-sm font-medium text-gray-700 mb-2">
                <i class="fas fa-barcode mr-2"></i>Serial Number
            </label>
            <input type="text"
                   name="serial_no"
                   id="serial_no"
                   value="{{ old('serial_no') }}"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                   placeholder="Enter product serial number">
            @error('serial_no')
                <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
            @enderror
        </div>

        <!-- IMEI Number Input -->
        <div>
            <label for="imei" class="block text-sm font-medium text-gray-700 mb-2">
                <i class="fas fa-mobile-alt mr-2"></i>IMEI Number
            </label>
            <input type="text"
                   name="imei"
                   id="imei"
                   value="{{ old('imei') }}"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                   placeholder="Enter 15-digit IMEI number">
            @error('imei')
                <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
            @enderror
        </div>
    </div>

    <div class="text-center text-gray-500 py-2">
        <i class="fas fa-info-circle mr-2"></i>Enter either Serial Number or IMEI
    </div>

    <!-- Camera Scanner Section -->
    <div id="scanner-section" class="hidden">
        <div id="reader" class="w-full border-2 border-dashed border-gray-300 rounded-lg p-2"></div>
        <div id="scanner-error" class="text-red-500 text-sm mt-2 text-center hidden"></div>
    </div>

    <div class="flex flex-col sm:flex-row gap-4 justify-center">
        <button type="submit"
                class="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center">
            <i class="fas fa-search mr-2"></i> Verify Product
        </button>
        <button type="button" id="scan-qr-btn"
                class="w-full sm:w-auto bg-purple-600 hover:bg-purple-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center">
            <i class="fas fa-qrcode mr-2"></i> Scan QR Code
        </button>
    </div>


    <!-- Verification Result (if product exists) -->
    @if(isset($product))
        <div class="bg-green-50 border border-green-200 rounded-lg p-6 mt-6">
            <div class="flex items-center mb-4">
                <i class="fas fa-check-circle text-green-500 text-2xl mr-3"></i>
                <h3 class="text-green-800 font-semibold text-lg">Product Verified Successfully!</h3>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">Product Name:</span>
                    <p class="text-gray-800">{{ $product->product_name }}</p>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">Serial No:</span>
                    <p class="text-gray-800 font-mono">{{ $product->serial_no }}</p>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">IMEI:</span>
                    <p class="text-gray-800 font-mono">{{ $product->imei }}</p>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">Quality:</span>
                    <p class="text-gray-800">{{ $product->quality }}</p>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">Color:</span>
                    <p class="text-gray-800">{{ is_array($product->color) ? implode(', ', $product->color) : $product->color }}</p>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <span class="font-medium text-gray-600">Status:</span>
                    <p class="text-gray-800">{{ $product->status }}</p>
                </div>
            </div>

            <div class="mt-4 flex gap-3">
                <a href="{{ route('products.report', $product->id) }}"
                   class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                    <i class="fas fa-file-pdf mr-2"></i>Download Report
                </a>
                <a href="{{ route('sticker.print') }}?serial_no={{ $product->serial_no }}"
                   class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
                    <i class="fas fa-print mr-2"></i>Print Sticker
                </a>
            </div>
        </div>
    @endif

    <!-- Error Message -->
    <x-modal name="error-modal" :show="false" focusable>
        <div class="p-6 text-center">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                <i class="fas fa-times text-red-600 text-xl"></i>
            </div>
            <h2 class="text-2xl font-bold text-gray-800 mt-4">Verification Failed</h2>

            <p class="mt-2 text-md text-gray-600">
                @if(session('error'))
                    {{ session('error') }}
                @endif
            </p>

            <div class="mt-6 flex justify-center">
                <button type="button" x-on:click="$dispatch('close')" class="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-8 rounded-lg transition duration-200">
                    Try Again
                </button>
            </div>
        </div>
    </x-modal>

    <!-- Quick Links -->
    {{-- <div class="text-center mt-4">
        <p class="text-gray-600 mb-3">Quick Access:</p>
        <div class="flex justify-center gap-4">
            <a href="{{ route('scanner.index') }}"
               class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors">
                <i class="fas fa-qrcode mr-2"></i>Scanner
            </a>
        </div>
    </div> --}}
</form>
</div>

<!-- Include HTML5 QR Code Scanner -->
<script src="https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const scanButton = document.getElementById('scan-qr-btn');
    const scannerSection = document.getElementById('scanner-section');
    const serialInput = document.getElementById('serial_no');
    const verificationForm = document.getElementById('verification-form');
    const scannerError = document.getElementById('scanner-error');
    let html5QrcodeScanner = null;
    let isScannerActive = false;

    scanButton.addEventListener('click', toggleScanner);

    function toggleScanner() {
        isScannerActive = !isScannerActive;
        if (isScannerActive) {
            startScanner();
            scannerSection.classList.remove('hidden');
            scanButton.innerHTML = '<i class="fas fa-stop mr-2"></i> Stop Scanner';
            scanButton.classList.replace('bg-purple-600', 'bg-red-600');
            scanButton.classList.replace('hover:bg-purple-700', 'hover:bg-red-700');
        } else {
            stopScanner();
            scannerSection.classList.add('hidden');
            scanButton.innerHTML = '<i class="fas fa-qrcode mr-2"></i> Scan QR Code';
            scanButton.classList.replace('bg-red-600', 'bg-purple-600');
            scanButton.classList.replace('hover:bg-red-700', 'hover:bg-purple-700');
        }
    }

    function startScanner() {
        if (!html5QrcodeScanner) {
            html5QrcodeScanner = new Html5Qrcode("reader");
        }

        scannerError.classList.add('hidden');

        html5QrcodeScanner.start(
            { facingMode: "environment" },
            {
                fps: 10,
                qrbox: { width: 250, height: 250 }
            },
            onScanSuccess,
            onScanFailure
        ).catch(err => {
            console.error(`Unable to start scanning, error: ${err}`);
            showError(`Unable to start camera. Please grant camera permissions.`);
            if(isScannerActive) toggleScanner(); // Revert button state on failure
        });
    }

    function stopScanner() {
        if (html5QrcodeScanner && html5QrcodeScanner.isScanning) {
            html5QrcodeScanner.stop().catch(err => {
                console.error("Failed to stop the scanner.", err);
            });
        }
    }

    function onScanSuccess(decodedText, decodedResult) {
        console.log(`Scan result: ${decodedText}`, decodedResult);
        stopScanner();

        let serial = decodedText;
        // Try to extract serial from a URL if the QR code contains one
        try {
            const url = new URL(decodedText);
            const serialFromParam = url.searchParams.get('serial') || url.searchParams.get('serial_no');
            if (serialFromParam) {
                serial = serialFromParam;
            }
        } catch (e) {
            // Not a URL, use the decoded text as is
        }

        serialInput.value = serial;
        verificationForm.submit();
    }

    function onScanFailure(error) {
        // This callback is called frequently, so we don't log every time.
        // console.warn(`Code scan error = ${error}`);
    }

    function showError(message) {
        scannerError.textContent = message;
        scannerError.classList.remove('hidden');
    }
});
</script>
