<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
import { VBtn } from "vuetify/components/VBtn";
import { useAlert } from "../composables/alert";
const props = defineProps({
  fileName: { type: String, required: false, default: "download" },
  sheetName: { type: String, required: false, default: "Sheet1" },
  modelValue: { type: Array, required: false },
  stringFields: { type: Array, required: false, default: () => [] },
  tooltip: { type: null, required: false, default: () => ({ text: "Export", location: "bottom" }) }
});
const alert = useAlert();
const loading = ref(false);
function exportFile() {
  if (props.modelValue && Array.isArray(props.modelValue) && props.modelValue.length > 0) {
    loading.value = true;
    try {
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(flattenNestedFields(props.modelValue));
      const fileName = `${props.fileName}.xlsx`;
      XLSX.utils.book_append_sheet(workbook, worksheet, props.sheetName);
      XLSX.writeFile(workbook, fileName);
    } catch (error) {
      alert?.addAlert({ message: `Export failed: ${error.message}`, alertType: "error" });
    } finally {
      loading.value = false;
    }
  } else {
    alert?.addAlert({ message: "Invalid or no data to export", alertType: "error" });
  }
}
function flattenNestedFields(items) {
  return items.map((item) => {
    return flattenObject(item);
  });
}
function flattenObject(obj, parentKey = "", separator = ".") {
  return Object.keys(obj).reduce((acc, key) => {
    const newKey = parentKey ? `${parentKey}${separator}${key}` : key;
    const value = obj[key];
    if (value && typeof value === "object" && !Array.isArray(value) && !props.stringFields.includes(newKey)) {
      Object.assign(acc, flattenObject(value, newKey, separator));
    } else {
      acc[newKey] = typeof value === "object" ? JSON.stringify(value) : value;
    }
    return acc;
  }, {});
}
</script>

<template>
  <VBtn
      v-bind="$attrs"
      color="primary"
      :loading="loading"
      :disabled="loading"
      text="Export CSV"
      @click="exportFile"
      v-tooltip="props.tooltip"
  >
    <template
        v-for="(_, name, index) in $slots"
        :key="index"
        #[name]="slotData"
    >
      <slot
          :name="name"
          v-bind="slotData || {}"
      />
    </template>
  </VBtn>
</template>
