<script setup lang="ts">
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head } from '@inertiajs/vue3';
import { QrcodeStream, QrcodeDropZone, QrcodeCapture } from 'vue-qrcode-reader'
import { nextTick, onMounted, ref, watch } from 'vue'
import axios from 'axios';
import {route} from 'ziggy-js';

// import { QrcodeStream } from 'vue-qrcode-reader';

// data
const result = ref('')
const error = ref('')
let remoteCode = ref(null);
const loading = ref(true);
const destroyed = ref(true);
const claimMsg = ref('');

onMounted(() => {
    destroyed.value = false;
})

// methods
const onDetect = detectedCodes => {
    console.log(detectedCodes)

    const [firstCode] = detectedCodes
    result.value = firstCode.rawValue

    getCodeData(result.value);
}

const getCodeData = (code) => {
    axios.get(route('qr.getCodeData', code))
        .then(res => {
            console.log('res', res);
            if (res.statusText && res.data) {
                remoteCode.value = res.data;
                destroyed.value = true;
            }
        }).catch(err => {
            console.log('Scan QR error ', err);
        })
}

const claimCode = (code) => {
    console.log(code);
    axios.post(route('qr.claim'), { code: code })
        .then(res => {
            console.log(res);
            if (res.status == 200 && res.data) {
                claimMsg.value = res.data;
                restScanner();
            }
        }).catch(err => {
            claimMsg.value = err.response.data.error;
            console.log(err);
        })
}

// const restScanner = () => {
//     result.value = '';
//     remoteCode.value = null;
// }

const restScanner = async () => {
    result.value = '';
    remoteCode.value = null;
    destroyed.value = true
    await nextTick();
    destroyed.value = false
    loading.value = true
}

const onCameraOn = () => {
    loading.value = false;
}


watch(result, (newResult: any) => {
    console.log(`x is ${newResult}`)
})

const onError = err => {
    error.value = `[${err.name}]: `

    if (err.name === 'NotAllowedError') {
        error.value += 'you need to grant camera access permission'
    } else if (err.name === 'NotFoundError') {
        error.value += 'no camera on this device'
    } else if (err.name === 'NotSupportedError') {
        error.value += 'secure context required (HTTPS, localhost)'
    } else if (err.name === 'NotReadableError') {
        error.value += 'is the camera already in use?'
    } else if (err.name === 'OverconstrainedError') {
        error.value += 'installed cameras are not suitable'
    } else if (err.name === 'StreamApiNotSupportedError') {
        error.value += 'Stream API is not supported in this browser'
    } else if (err.name === 'InsecureContextError') {
        error.value += 'Camera access is only permitted in secure context. Use HTTPS or localhost rather than HTTP.'
    } else {
        error.value += err.message
    }
}
</script>

<template>
    <Head title="Dashboard" />

    <AuthenticatedLayout>
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Scan</h2>
        </template>

        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">

                    <qrcode-stream @detect="onDetect" @error="onError" @camera-on="onCameraOn" v-if="!destroyed">
                        <div class="loading-indicator" v-if="loading">Loading...</div>
                    </qrcode-stream>

                    <!-- <button @click="restScanner">Reset</button> -->


                    <template v-if="remoteCode">
                        <div v-if="!remoteCode.claimed" class="p-3 mb-4 bg-green-600 text-white inline-block rounded">
                            Available</div>
                        <div v-if="remoteCode.claimed" class="p-3 mb-4 bg-red-600 text-white inline-block rounded">Already
                            Claimed
                        </div>

                        <h3>Code : {{ remoteCode.code }}</h3>
                        <h3>Claimed : {{ (remoteCode.claimed) ? 'Already Claimed' : 'Available for the claim' }}</h3>
                        <h3>Claimed at : {{ remoteCode.claimed_at }}</h3>

                        <button v-if="!remoteCode.claimed" class="bg-orange-500 p-2 mt-4 rounded mr-3" type="button"
                            @click="claimCode(remoteCode.code)">Mark As
                            Claim</button>

                    </template>
                    <button class="bg-green-500 p-2 mt-4 rounded" type="button" @click="restScanner()">Scan New</button>

                    <p class="error">{{ error }}</p>

                    <p v-if="claimMsg">{{ claimMsg }}</p>

                    <!-- <qrcode-drop-zone></qrcode-drop-zone>
                    <qrcode-capture></qrcode-capture> -->

                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
