<script setup>
import { computed, ref, useAttrs } from "vue";
import Textarea from "primevue/textarea";

defineOptions({ inheritAttrs: false });

const props = defineProps({
  label: { type: String, default: "" },
  description: { type: String, default: "" },
  modelValue: { type: String, default: "" },
  error: { type: String, default: "" },
  required: { type: Boolean, default: false },
  id: { type: String, default: undefined },
  class: { type: [String, Object, Array], default: "w-full" },
});

const attrs = useAttrs();

const emit = defineEmits(["update:modelValue"]);

const fallbackId = ref(
  `base-textarea-${Math.random().toString(36).slice(2, 11)}`,
);
const inputId = computed(() => props.id ?? fallbackId.value);
const invalidState = computed(() => !!props.error || !!attrs.invalid);
const errorId = computed(() => `${inputId.value}-error`);

const textareaAttrs = computed(() => {
  const rest = { ...attrs };
  delete rest.class;
  delete rest.style;
  delete rest.invalid;
  delete rest["onUpdate:modelValue"];
  return {
    fluid: true,
    rows: 3,
    ...rest,
  };
});
</script>

<template>
  <div class="flex flex-col" :class="props['class']">
    <div v-if="label || description" class="flex flex-col mb-2">
      <label
        v-if="label"
        :for="inputId"
        class="block text-surface-950 dark:text-surface-0 text-md font-medium leading-7"
      >
        {{ label
        }}<span v-if="required" class="text-red-500" aria-hidden="true">
          *
        </span>
      </label>
      <div
        v-if="description"
        class="text-surface-500 dark:text-surface-400 text-base font-normal leading-normal mt-1"
      >
        {{ description }}
      </div>
    </div>
    <Textarea
      :id="inputId"
      v-bind="textareaAttrs"
      :model-value="modelValue"
      :invalid="invalidState"
      :required="required"
      :aria-invalid="invalidState"
      :aria-describedby="error ? errorId : undefined"
      @update:model-value="emit('update:modelValue', $event)"
    />
    <small
      v-if="error"
      :id="errorId"
      class="block text-red-500 mt-1 text-sm"
      role="alert"
      >{{ error }}</small
    >
  </div>
</template>
