<template>
  <field v-bind="$props">
    <textarea
      ref="textArea"
      :value="modelValue"
      role="input"
      :class="classes"
      :required="required"
      :placeholder="placeholder"
      :disabled="disabled"
      @input="onInput"
      @keydown.enter.stop
      cols="10"
    >
      {{ modelValue }}
    </textarea>
  </field>
</template>

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

export interface Props extends FieldComponentProps {
  modelValue: string;
  placeholder?: string;
}

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

const textArea: Ref<HTMLElement | null> = ref(null);

const $emits = defineEmits<{
  (e: 'update:modelValue', value: string): void;
}>();

const onInput = (e: Event) => {
  if (!props.disabled)
    $emits('update:modelValue', (e?.target as HTMLInputElement).value);
};

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

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

defineExpose({
  setFocus,
});
</script>

<style scoped lang="scss">
.field__input {
  textarea {
    display: flex;
    align-items: center;

    width: 100%;
    padding: var(--field-padding);
    border-radius: var(--bms-border-radius);
    border: 1px solid var(--field-border-color);
    background-color: var(--textarea-background-color);
    min-height: 96px;
    outline: none;
    font: inherit;
    color: inherit;
    &:hover {
      --field-border-color: var(--bms-grey-100);
    }

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

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

    &.is-disabled {
      --field-border-color: var(--bms-field-disabled-border-color);
      --textarea-background-color: var(--bms-field-disabled-background);
      color: var(--bms-field-disabled-text-color);
      cursor: text;

      textarea:disabled {
        opacity: 1;
        -webkit-text-fill-color: currentColor;
      }
    }
    &.is-small {
      min-height: 56px;
    }
  }
}
</style>
