<template>
  <div class="column" :class="attrs.class" :style="attrs.style">
    <div class="col">
      <q-select
        ref="selectRef"
        v-model="model"
        hide-bottom-space
        hide-dropdown-icon
        label-color="secondary"
        lazy-rules="ondemand"
        v-bind="selectAttrs"
        :bg-color
        :class="[inputClass, { 'required-field': required }]"
        :error="!!error"
        :error-message="errorMessage"
        :label
        :outlined
        :popup-content-class="popupContentClass"
        :rules
        @update:model-value="error = null"
      >
        <template v-for="(_, slotName) in $slots" #[slotName]="scope">
          <slot :name="slotName" v-bind="scope" />
        </template>

        <template #append>
          <q-icon :name="dropdownIcon" color="secondary" />
        </template>
      </q-select>
    </div>
  </div>
</template>

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

defineOptions({
  inheritAttrs: false,
});

const {
  bgColor,
  dropdownIcon,
  inputClass,
  label,
  outlined,
  popupContentClass,
  rules,
} = defineProps({
  bgColor: {
    type: String,
    default: "white",
  },
  dropdownIcon: {
    type: String,
    default: "mdi-chevron-down",
  },
  inputClass: {
    type: String,
    default: null,
  },
  label: {
    type: String,
    default: "",
  },
  outlined: {
    type: Boolean,
    default: true,
  },
  popupContentClass: {
    type: String,
    default: null,
  },
  rules: {
    type: Array,
    default: () => [],
  },
});

const attrs = useAttrs();

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

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

const selectRef = ref(null);
const required = ref(false);

const selectAttrs = 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);
});

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

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

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