<script setup lang="ts">
import * as z from 'zod'
import { useUIValidation } from '#adata-ui/composables/useUIValidation'

const props = defineProps<{
  isError?: boolean,
}>()

const emit = defineEmits<{
  (e: 'onSubmit'): void
}>()

const { t } = useI18n()

const note = defineModel<string>({ required: true })
const isLoading = defineModel<boolean>('loading')

const schema = z.object({
  note: z.string().nonempty(t('forms.leaveNote.errors.required')).max(100, t('forms.leaveNote.errors.maxLength', { n: 100 })),
})

const submitted = ref(false)

const { validation, getError } = useUIValidation(
  schema,
  () => ({
    note: note.value,
  }),
  submitted,
)

async function onSubmit() {
  submitted.value = true
  if (validation.value) return
  emit('onSubmit')
}

defineExpose({
  reset: () => (submitted.value = false),
})
</script>

<template>
  <div class="flex flex-col items-start rounded-md">
    <p class="text-sm font-semibold mb-4">
      {{ t('forms.leaveNote.title') }}
    </p>
    <a-textarea
      v-model="note"
      :label="t('forms.leaveNote.placeholder')"
      :error="getError('note')"
      class="mb-2 min-h-[120px]"
      resizeable="none"
      clearable
      required
    >
      <template #alert>
        <a-alert
          v-if="isError || getError('note')"
          color="red"
          class="mt-1"
        >
          {{ getError('note') || (isError ? t('forms.leaveNote.limit') : '') }}
        </a-alert>
      </template>
    </a-textarea>
    <a-button
      :disabled="!note.trim() && isLoading"
      class="w-full sm:w-auto"
      size="lg"
      :loading="isLoading"
      @click="onSubmit"
    >
      {{ t('actions.send') }}
    </a-button>
  </div>
</template>
