<template>
  <div class="default-image-picker">
    <div class="text-caption text-grey-6 q-mb-xs">{{ label }}</div>

    <CustomFileInput
      v-model="model"
      :accept="accept"
      :clearable="clearable"
      :dense="dense"
      :error="error"
      :error-message="errorMessage"
      :outlined="outlined"
      @update:model-value="handleFile"
    >
      <template #append>
        <q-icon name="search" />
      </template>
    </CustomFileInput>

    <div class="text-caption text-grey-6 q-mt-md q-mb-xs">
      Pré - Visualização
    </div>

    <div class="preview-area flex flex-center">
      <img v-if="previewUrl" :src="previewUrl" class="preview-image" />
    </div>
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref } from "vue";
import CustomFileInput from "./CustomFileInput.vue";

const { accept, clearable, dense, error, errorMessage, label, outlined } =
  defineProps({
    accept: { type: String, default: "image/*" },
    clearable: { type: Boolean, default: true },
    dense: { type: Boolean, default: true },
    error: { type: [String, Object, Array, Boolean], default: null },
    errorMessage: { type: String, default: undefined },
    label: { type: String, default: "Personalizar" },
    outlined: { type: Boolean, default: true },
  });

const model = defineModel({ type: [File, null] });
const previewModel = defineModel("previewUrl", { type: String, default: null });
const previewUrl = ref(null);

const handleFile = (file) => {
  if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);

  previewUrl.value = file ? URL.createObjectURL(file) : null;

  previewModel.value = previewUrl.value;
}

onBeforeUnmount(() => {
  if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
});
</script>

<style scoped>
.preview-area {
  min-height: 180px;
  border: 1px dashed #c7c7c7;
  border-radius: 8px;
  background: #fafafa;
}

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