<template>
  <div class="column items-center q-gutter-y-sm">
    <q-avatar size="200px" font-size="80px" color="grey-4" text-color="grey-7">
      <q-img
        v-if="previewUrl"
        :src="previewUrl"
        spinner-color="primary"
        style="height: 100%; width: 100%"
      />

      <q-icon name="mdi-camera-plus" color="primary" />
    </q-avatar>

    <q-btn
      :label="previewUrl ? 'Alterar foto' : 'Escolher foto'"
      color="primary"
      outline
      no-caps
      class="q-mt-md"
      @click="triggerFilePick"
    />

    <q-file
      ref="fileInputRef"
      v-model="selectedFile"
      class="hidden"
      accept="image/*"
    />
  </div>
</template>

<script setup>
import { ref, watch } from "vue";

const model = defineModel({
  type: [String, Object],
  default: null,
});

const fileInputRef = ref(null);
const selectedFile = ref(null);

const previewUrl = ref(null);

const generatePreview = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    previewUrl.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

watch(
  model,
  (newValue) => {
    if (typeof newValue === "string") {
      previewUrl.value = newValue;
    } else if (newValue instanceof File) {
      generatePreview(newValue);
    } else {
      previewUrl.value = null;
    }
  },
  { immediate: true },
);

watch(selectedFile, (newFile) => {
  if (newFile) {
    model.value = newFile;
  }
});

const triggerFilePick = () => {
  fileInputRef.value?.pickFiles();
};
</script>

<style scoped>
.hidden {
  display: none;
}
</style>
