<template>
  <BmsInputText
    ref="input"
    v-model="search"
    :placeholder="placeholder"
    :errors="errors"
    :disabled="disabled"
  >
    <template #icon-start>
      <Search />
    </template>

    <template v-if="search && !disabled" #icon-end>
      <X class="clean-icon" @click="search = ''" />
    </template>
  </BmsInputText>
</template>

<script setup lang="ts">
import { Search, X } from 'lucide-vue-next';
import { Ref, computed, ref } from 'vue';
import BmsInputText from './BmsInputText.vue';
import { Caption } from '@/models/caption.model';

export interface Props {
  modelValue: string;
  placeholder?: string;
  disabled?: boolean;
  errors?: (string | Caption)[];
}

const input: Ref<typeof BmsInputText | null> = ref(null);

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Rechercher...',
});
const emit = defineEmits<{ (e: 'update:modelValue', value: string): void }>();

const search = computed({
  get() {
    return props.modelValue;
  },
  set(value: string) {
    emit('update:modelValue', value);
  },
});

const setFocus = () => {
  if (input.value) {
    input.value.setFocus();
  }
};

defineExpose({
  setFocus,
});
</script>
<style lang="scss" scoped>
.clean-icon:hover {
  cursor: pointer;
}
</style>
