<template>
  <div class="ais-control" :class="{
    leadingIcon: hasLeadingIcon, trailingIcon: hasLeadingIcon, invalid: isInvalid
  }">
    <div v-if="hasLeadingIcon" class="econ left">
      <AisIcon :icon="props.icon" class="" />
    </div>

    <BaseSelect
      v-model="model"
      v-bind="$props"
      @load="emit('load', $event)"
      @change="emit('change', $event)"
      :class="inputClasses"
      :disabled="disabled"
      :invalid="isInvalid"
    >
      <template #head>
        <slot name="head" />
      </template>

      <slot name="default" />
    </BaseSelect>

    <div v-if="hasTrailingIcon" class="econ right">
      <AisIcon :icon="trailingIcon" class="" />
    </div>
  </div>
</template>

<script setup>
  import BaseSelect from '@/components/select/BaseSelect.vue'
  import AisIcon from '@/components/icon/AisIcon.vue'
  import {selectProps} from "@/components/select/select-props";
  import {controlProps} from "@/util/controls";
  import {iconProps} from "@c/icon/ais-icons";
  import {computed, inject} from "vue";
  import {useVModel} from "@vueuse/core";
  import {CONTROL_INVALID} from "@/util/controls";
  import {useSize} from "@/composables/useInjections";

  const props = defineProps({
    ...selectProps,
    ...controlProps,
    ...iconProps,
  })

  const emit = defineEmits([
    'update:modelValue',
    'load',
    'change'
  ])

  const model = useVModel(props, 'modelValue', emit)
  const selectSize = useSize(props, 'md')

  const injectedInvalid = inject(CONTROL_INVALID, false)
  const isInvalid = computed(() => props.invalid || injectedInvalid.value)

  const hasLeadingIcon = computed(() => !!props.icon)
  const hasTrailingIcon = computed(() => !!props.status || isInvalid.value)

  const trailingIcon = computed(() => isInvalid.value ? 'error' : props.status)

  const inputClasses = computed(() => {
    return [selectSize.value]
  })

</script>
