<script setup>
import { ref, watch } from "vue";
import { useAlert } from "../composables/alert";
const props = defineProps({
  modelValue: { type: String, required: false }
});
const emit = defineEmits(["update:modelValue", "decode"]);
const alert = useAlert();
const scanCode = ref(false);
const currentValue = ref();
const handleData = (data) => {
  currentValue.value = data;
  scanCode.value = false;
  emit("decode", data);
};
const handleError = (error) => {
  alert?.addAlert({ message: error, alertType: "error" });
};
watch(() => props.modelValue, () => {
  currentValue.value = props.modelValue;
}, { immediate: true });
watch(currentValue, (newValue) => {
  emit("update:modelValue", newValue);
});
</script>

<template>
  <v-text-field
    v-model="currentValue"
    v-bind="$attrs"
    append-inner-icon="mdi mdi-qrcode-scan"
    @click:append-inner="scanCode = true"
  />
  <v-dialog
    v-model="scanCode"
    width="auto"
  >
    <BarcodeReader
      @decode="handleData"
      @error="handleError"
    />
  </v-dialog>
</template>
