<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="min-width: 400px">
      <DefaultDialogHeader title="Trocar Imagem" @close="onDialogCancel" />

      <q-card-section class="q-pt-none q-pb-sm">
        <div class="text-caption text-grey-6 q-mb-xs">Personalizar</div>
        <q-file
          v-model="selectedFile"
          accept="image/*"
          outlined
          dense
          placeholder="Buscar no Desktop"
          @update:model-value="onFileSelected"
        >
          <template #append>
            <q-icon name="search" />
          </template>
        </q-file>
      </q-card-section>

      <q-card-section class="q-pt-none">
        <div class="text-caption text-grey-6 q-mb-xs">Pré - Visualização</div>
        <div class="preview-area flex flex-center">
          <img v-if="previewUrl" :src="previewUrl" class="preview-image" />
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn outline color="primary" label="Cancelar" @click="onDialogCancel" />
        <q-btn color="primary" label="Salvar" :disable="!selectedFile" @click="onSave" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();

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

function onFileSelected(file) {
  if (!file) {
    previewUrl.value = null;
    return;
  }
  const reader = new FileReader();
  reader.onload = (e) => {
    previewUrl.value = e.target.result;
  };
  reader.readAsDataURL(file);
}

function onSave() {
  onDialogOK({ file: selectedFile.value, previewUrl: previewUrl.value });
}
</script>

<style scoped>
.preview-area {
  width: 100%;
  height: 200px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fafafa;
  overflow: hidden;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>
