<script setup>
import * as XLSX from "xlsx";
import { ref, computed, useAttrs } from "vue";
import { useLightInputDefaults } from "../../composables/useLightProps";
defineOptions({ inheritAttrs: false });
const props = defineProps({
  label: { type: String, required: false },
  hint: { type: String, required: false },
  disable: { type: Boolean, required: false }
});
const attrs = useAttrs();
const modelValue = defineModel({ type: Array, ...{ default: () => [] } });
const loading = ref(false);
const errorMsg = ref(null);
const fileInput = ref(null);
const showView = ref(false);
const hasFile = computed(() => modelValue.value.length > 0);
const base = useLightInputDefaults(props, attrs, []);
const fieldProps = computed(() => ({
  ...base.value,
  loading: loading.value,
  error: !!errorMsg.value,
  errorMessage: errorMsg.value ?? void 0
}));
const onChange = async () => {
  const f = fileInput.value?.files?.[0];
  if (!f) return;
  loading.value = true;
  errorMsg.value = null;
  try {
    const data = await f.arrayBuffer();
    const workbook = XLSX.read(data);
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    modelValue.value = XLSX.utils.sheet_to_json(sheet);
  } catch (e) {
    errorMsg.value = e?.message ?? "Failed to parse file";
    modelValue.value = [];
  } finally {
    loading.value = false;
  }
};
const onClear = () => {
  modelValue.value = [];
  errorMsg.value = null;
  if (fileInput.value) fileInput.value.value = "";
};
</script>

<template>
    <q-field v-bind="fieldProps" :model-value="modelValue">
        <template #control>
            <template v-if="!hasFile">
                <input type="file" accept=".xlsx,.xls" @change="onChange" ref="fileInput" />
            </template>
            <template v-else>
                {{ modelValue.length }} records loaded
            </template>
        </template>

        <template #prepend v-if="hasFile">
            <q-icon name="sym_o_table_view" @click="showView = true" class="cursor-pointer" />
        </template>

        <template #append v-if="hasFile">
            <q-icon name="sym_o_close" @click="onClear" class="cursor-pointer" />
        </template>

        <q-dialog v-model="showView" full-width>
            <q-card>
                <q-bar class="bg-primary text-white">
                    <div>{{ label ?? "Preview" }}</div>
                    <q-space />
                    <q-btn dense flat icon="sym_o_close" v-close-popup />
                </q-bar>
                <q-card-section>
                    <q-table :rows="modelValue" dense separator="cell" flat bordered />
                </q-card-section>
            </q-card>
        </q-dialog>
    </q-field>
</template>
