﻿<script setup lang="ts">
import { computed, useAttrs } from 'vue'

defineOptions({ inheritAttrs: false })

const props = withDefaults(
  defineProps<{
    modelValue: string
    placeholder?: string
    rows?: number
    maxLength?: number
    label?: string
    disabled?: boolean
  }>(),
  {
    placeholder: '',
    rows: 4,
    label: '',
    disabled: false,
  },
)

const emit = defineEmits<{ 'update:modelValue': [string] }>()
const attrs = useAttrs()
const uid = `textarea-${Math.random().toString(36).slice(2, 9)}`

const textareaId = computed(() => (attrs.id as string) || uid)

const textareaClasses = computed(() => [
  'input-magic w-full px-4 py-3 rounded-xl text-gray-700 placeholder-gray-400 focus:outline-none resize-none',
  props.disabled ? 'opacity-60 cursor-not-allowed' : '',
])

const passthroughAttrs = computed(() => {
  const { class: _class, id: _id, ...rest } = attrs
  return rest
})
</script>

<template>
  <div class="space-y-2">
    <label v-if="props.label" :for="textareaId" class="text-sm font-medium text-gray-700">
      {{ props.label }}
    </label>
    <div class="relative">
      <textarea
        :id="textareaId"
        :rows="props.rows"
        :placeholder="props.placeholder"
        :value="props.modelValue"
        :maxlength="props.maxLength"
        :disabled="props.disabled"
        :class="[textareaClasses, attrs.class]"
        v-bind="passthroughAttrs"
        @input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
      ></textarea>
      <div v-if="props.maxLength" class="absolute bottom-3 right-4 text-xs text-gray-400">
        {{ props.modelValue.length }} / {{ props.maxLength }}
      </div>
    </div>
  </div>
</template>
