<template>
  <field v-bind="$props">
    <span class="select-wrapper" :class="classes">
      <slot name="input"> </slot>
    </span>
    <template #datalist>
      <FieldDatalist
        v-show="open"
        :options="options"
        :is-input-focused="open"
        :small="small"
        @select="selectItem"
      >
        <template #option="{ option }: { option: any }">
          <slot name="option" :option="option"></slot>
        </template>
      </FieldDatalist>
    </template>
  </field>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import FieldDatalist from '@/plugins/field/FieldDatalist.vue';
import { InputOption } from '@/models';
import { FieldComponentProps } from '@/plugins/field/field-component.model';

export interface Props extends FieldComponentProps {
  options: InputOption[];
  optional?: boolean;
  placeholder?: string;
  open?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  label: '',
  disabled: false,
  required: false,
  small: false,
  open: false,
});

const emits = defineEmits<{
  select: [selectedItem: any];
}>();

const classes = computed(() => {
  return { 'is-error': props.errors?.length, 'is-disabled': props.disabled };
});

const selectItem = (option: any) => {
  emits('select', option);
};
</script>

<style lang="scss" scoped>
.field__input {
  --field-border-color: var(--bms-grey-50);
  --field-border-color-active: var(--bms-main-100);
  --input-background-color: var(--bms-white);

  .select-wrapper {
    width: 100%;
    padding: 0 0 0 var(--field-padding);
    border-radius: var(--bms-border-radius);
    border: 1px solid var(--field-border-color);
    background-color: var(--input-background-color);
    min-height: var(--field-height);

    display: flex;
    align-items: center;
    justify-content: space-between;

    &:hover {
      --field-border-color: var(--bms-grey-100);
    }

    &:has(input:focus) {
      --field-border-color: var(--field-border-color-active);
    }

    &.is-error {
      --field-border-color: var(--bms-red-100);
      --input-background-color: var(--bms-red-25);
    }

    &.is-disabled {
      --field-border-color: var(--bms-field-disabled-border-color);
      --input-background-color: var(--bms-field-disabled-background);
      color: var(--bms-field-disabled-text-color);
      pointer-events: none;

      input:disabled {
        opacity: 1;
        -webkit-text-fill-color: currentColor;
      }
    }
  }
}
</style>
