<template>
  <div class="column" :class="attrs.class" :style="attrs.style">
    <div class="col">
      <q-input
        ref="inputRef"
        v-model="model"
        v-bind="inputAttrs"
        hide-bottom-space
        label-color="secondary"
        color="secondary"
        :label
        :error="!!error"
        :error-message="errorMessage"
        :rules
        :outlined
        :bg-color
        :class="inputClass"
        :input-class="nativeInputClass"
        @update:model-value="error = null"
      >
        <template #append>
          <slot name="append">
            <q-icon v-if="icon" :name="icon" size="sm" color="secondary" />
          </slot>
        </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, bgColor, outlined } =
  defineProps({
    label: {
      type: String,
      default: "",
    },
    icon: {
      type: String,
      default: "",
    },
    rules: {
      type: Array,
      default: () => [],
    },
    nativeInputClass: {
      type: String,
      default: null,
    },
    inputClass: {
      type: String,
      default: null,
    },
    bgColor: {
      type: String,
      default: "white",
    },
    outlined: {
      type: Boolean,
      default: false,
    },
  });

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 lang="scss">
:deep(.q-field--outlined.q-field--rounded .q-field__control) {
  border-radius: 8px;
}
</style>
