<template>
  <div class="column" :class="attrs.class" :style="attrs.style">
    <div class="col">
      <q-input
        ref="inputRef"
        v-model="model"
        v-bind="inputAttrs"
        :label
        label-color="secondary"
        :error="!!error"
        :error-message="errorMessage"
        :rules
        hide-bottom-space
        :class="inputClass"
        :input-class="nativeInputClass"
        @update:model-value="error = null"
      >
        <template v-for="(_, slotName) in $slots" #[slotName]>
          <slot :name="slotName" />
        </template>

        <template #append>
          <q-icon v-if="icon" :name="icon" size="sm" color="secondary" />
        </template>
      </q-input>
    </div>
  </div>
</template>

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

defineOptions({
  inheritAttrs: false,
});

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

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>
