<template>
  <div class="column no-wrap col" :class="attrs.class" :style="attrs.style">
    <div v-if="label || $slots.label" class="q-pl-xs">
      <slot name="label">
        <span>{{ label }}</span>
      </slot>
      <span v-if="required" class="text-negative q-ml-xs">*</span>
    </div>
    <q-input
      ref="inputRef"
      v-model="model"
      v-bind="inputAttrs"
      :error="!!error"
      :error-message="errorMessage"
      :rules
      hide-bottom-space
      class="input-violet"
      :class="inputClass"
      :input-class="nativeInputClass"
      :mask="mask"
      @update:model-value="error = null"
    >
      <template v-for="(_, slotName) in $slots" #[slotName]>
        <slot :name="slotName" />
      </template>
    </q-input>
  </div>
</template>

<script setup>
import {
  ref,
  onBeforeMount,
  useAttrs,
  computed,
  watch,
  useTemplateRef,
} from "vue";

defineOptions({
  inheritAttrs: false,
});

const { label, nativeInputClass, inputClass, rules } = defineProps({
  label: {
    type: String,
    default: "",
  },
  rules: {
    type: Array,
    default: () => [],
  },
  nativeInputClass: {
    type: String,
    default: null,
  },
  inputClass: {
    type: String,
    default: null,
  },
  mask: {
    type: [String],
    default: undefined,
  },
});

const attrs = useAttrs();

const inputRef = useTemplateRef("inputRef");

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

const required = ref(false);

const inputAttrs = computed(() => {
  // eslint-disable-next-line
  const { class: _, style: __, ...rest } = attrs;
  return rest;
});

const errorMessage = computed(() => {
  if (error.value == null) {
    return void 0;
  }
  if (typeof error.value === "boolean") {
    return void 0;
  }
  return String(error.value);
});

watch(
  () => rules,
  (values) => {
    values.forEach((r) => {
      if (r?.$id === "required") return (required.value = true);
    });
  },
);

onBeforeMount(() => {
  rules.forEach((r) => {
    if (r?.$id === "required") return (required.value = true);
  });
});

defineExpose({
  inputRef,
});
</script>

<style scoped></style>
