<template>
  <div class="column" :class="attrs.class" :style="attrs.style">
    <div class="col">
      <q-select
        ref="selectRef"
        v-model="model"
        :label
        label-color="secondary"
        v-bind="selectAttrs"
        :error="!!error"
        :error-message="errorMessage"
        :rules
        :outlined
        hide-bottom-space
        :bg-color
        :class="inputClass"
        :popup-content-class="popupContentClass"
        hide-dropdown-icon
        @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 { ref, onBeforeMount, useAttrs, computed } from "vue";

defineOptions({
  inheritAttrs: false,
});

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

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>
