<template>
  <div class="ais-input ais-control"
       :class="{
          leadingIcon: hasLeadingIcon,
          trailingIcon: hasTrailingIcon,
          invalid: isInvalid
  }">
    <div v-if="hasLeadingIcon" class="econ left">
      <AisIcon :icon="icon" :class="{'text-danger': false}" />
    </div>

    <BaseInput
        ref="inputElement"
        v-model="model"
        :type="props.type"
        :id="id"
        :name="name"
        :placeholder="placeholder"
        :disabled="inputDisabled"
        :required="required"
        :invalid="isInvalid"
        :autocomplete="autocomplete"
        v-bind="$attrs"
        :class="inputClasses"
    />
    <slot name="status" :status="status" :icon="trailingIcon" :hasIcon="hasTrailingIcon">
      <div v-if="hasTrailingIcon" class="econ right">
        <AisIcon :icon="trailingIcon" class="" />
      </div>
    </slot>
  </div>
</template>

<script setup>
  import { ref, computed } from "vue";
  import { useVModel } from '@vueuse/core'

  import BaseInput from '@/components/input/BaseInput.vue'
  import AisIcon from '@/components/icon/AisIcon.vue'
  import {inputProps} from "@/components/input/input-props";
  import {controlProps} from "@/util/controls";
  import {iconProps} from "@c/icon/ais-icons";
  import { useSize, useDisabled, useInvalid} from "@/composables/useInjections";

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

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

  const model = useVModel(props, 'modelValue', emit)

  const inputSize = useSize(props, 'md')
  const inputDisabled = useDisabled(props)
  const isInvalid = useInvalid(props)

  const hasLeadingIcon = !!props.icon
  const hasTrailingIcon = computed(() => !!props.status || isInvalid.value)
  const trailingIcon = computed(() => isInvalid.value ? 'error' : props.status)

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

  const inputElement = ref(null)
  const focus = () => inputElement.value.focus()
  defineExpose({ focus })

</script>
