<template>
  <q-file
    v-model="model"
    v-bind="attrs"
    :accept
    :class="{ 'required-field': required }"
    :clearable
    :dense
    :error="!!error"
    :error-message="normalizedErrorMessage"
    :label
    :outlined
    :rules
    color="secondary"
    hide-bottom-space
    label-color="secondary"
    lazy-rules="ondemand"
    @update:model-value="error = null"
  >
    <template #prepend>
      <slot name="prepend">
        <q-icon v-if="prependIcon" color="secondary" :name="prependIcon" />
      </slot>
    </template>

    <template v-for="(_, slotName) in $slots" #[slotName]="scope">
      <slot
        v-if="slotName !== 'prepend'"
        v-bind="scope ?? {}"
        :name="slotName"
      />
    </template>
  </q-file>
</template>

<script setup>
import { computed, useAttrs } from "vue";

defineOptions({ name: "CustomFileInput", inheritAttrs: false });

const {
  accept,
  clearable,
  dense,
  errorMessage,
  label,
  outlined,
  prependIcon,
  rules,
} = defineProps({
  accept: { type: String, default: "" },
  clearable: { type: Boolean, default: false },
  dense: { type: Boolean, default: false },
  errorMessage: { type: String, default: undefined },
  label: { type: String, default: "Arquivo" },
  outlined: { type: Boolean, default: true },
  prependIcon: { type: String, default: "mdi-paperclip" },
  rules: { type: Array, default: () => [] },
});

const attrs = useAttrs();

const model = defineModel({ type: [File, Array, null] });

const error = defineModel("error", {
  type: [String, Object, Array, Boolean, null],
});

const normalizedErrorMessage = computed(() => {
  if (errorMessage != null) return errorMessage;

  if (error.value == null || typeof error.value === "boolean") return undefined;

  return String(error.value);
});

const required = computed(() => rules.some((rule) => rule?.$id === "required"));
</script>

<style scoped>
:deep(.required-field .q-field__label::after) {
  color: var(--q-negative);
  content: " *";
}
</style>
