<script lang="ts" setup>
import { ref } from 'vue';
import MainButton from './MainButton.vue';

const emit = defineEmits<{
  (e: 'click', v: MouseEvent): void;
  (e: 'fileSelected', v: File[]): void;
}>();
defineProps<{
  iconOnly?: boolean;
  solid?: boolean;
  outlined?: boolean;
  disabled?: boolean;
  dark?: boolean;
  importFile?: boolean;

  label?: string;
  icon?: string;
}>();

const inputRef = ref<HTMLInputElement | null>(null);

function triggerFileInput() {
  inputRef.value?.click();
}

function handleFileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files;
  if (files && files.length > 0) {
    emit('fileSelected', Array.from(files));
  }
}
</script>

<template>
  <MainButton
    @click="(e) => (importFile ? triggerFileInput() : $emit('click', e))"
    v-bind="{ ...$props, ...$attrs }"
    :icon="icon || 'mdi-import'"
    color="var(--info-bg)"
    :title="iconOnly ? $t('general.import') : undefined"
  >
    {{ label || $t('general.import') }}
  </MainButton>

  <input
    ref="inputRef"
    type="file"
    @change="(e) => handleFileChange(e)"
    hidden
    accept=".xls, .xlsx , .csv"
    multiple
  />
</template>
