<script setup>
import { computed, ref, useAttrs } from "vue";
import { VBtn } from "vuetify/components/VBtn";
import { useAlert } from "../../composables/alert";
import { useHostAgent } from "../../composables/hostAgent";
const props = defineProps({
  withPhoto: { type: Boolean, required: false, default: false },
  reader: { type: [String, null], required: false, default: null },
  disableWhileLoading: { type: Boolean, required: false, default: true }
});
const emit = defineEmits(["read", "error", "loading"]);
const attrs = useAttrs();
const host = useHostAgent();
const loading = ref(false);
const disabled = computed(() => props.disableWhileLoading ? loading.value : false);
async function onClick(ev) {
  if (ev.defaultPrevented) return;
  try {
    loading.value = true;
    emit("loading", true);
    const payload = props.withPhoto ? await host.getIdCardInfoAndPhoto(props.reader ?? void 0) : await host.getIdCardInfo(props.reader ?? void 0);
    emit("read", payload);
  } catch (e) {
    emit("error", e);
    const msg = e?.data?.detail || e?.data?.title || e?.message || "ID card read failed";
    useAlert()?.addAlert({ message: msg, alertType: "error" });
  } finally {
    loading.value = false;
    emit("loading", false);
  }
}
</script>

<template>
  <!--
    Extends Vuetify VBtn:
    - All unknown attrs (size, class, etc.) pass through via v-bind="attrs"
    - You can override content via default slot; label+icon is fallback
  -->
  <v-btn
      v-bind="attrs"
      class="idcard-btn"
      :loading="loading"
      :disabled="disabled || attrs.disabled"
      @click="onClick"
  >
    <template
        v-for="(_, name, index) in $slots"
        :key="index"
        #[name]="slotData"
    >
      <slot
          :name="name"
          v-bind="slotData || {}"
      />
    </template>
  </v-btn>
</template>
