<template>
  <div class="mt-4">
    <div v-if="isAuthenticated">
      <UForm :state="form" @submit="onSubmit">
        <UFormField class="w-full">
          <UTextarea
            v-model="form.content"
            :placeholder="placeholder"
            :minrows="3"
            :maxrows="8"
            class="w-full"
            autoresize
          />
        </UFormField>

        <div class="mt-2 flex justify-between items-center">
          <span class="text-xs text-gray-500 dark:text-gray-400">
            {{ form.content.length }}/2000
          </span>
          <div class="flex gap-2">
            <UButton
              v-if="parentId"
              variant="ghost"
              size="sm"
              @click="$emit('cancel')"
            >
              取消
            </UButton>
            <UButton
              type="submit"
              color="indigo"
              size="sm"
              :loading="submitting"
              :disabled="!form.content.trim()"
            >
              {{ parentId ? '回复' : '发表评论' }}
            </UButton>
          </div>
        </div>
      </UForm>
    </div>

    <div v-else class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 text-center">
      <p class="text-gray-600 dark:text-gray-400 mb-2">登录后发表评论</p>
      <UButton to="/login" color="indigo" size="sm">立即登录</UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  articleId: number
  parentId?: number
  placeholder?: string
}>()

const emit = defineEmits<{
  submitted: []
  cancel: []
}>()

const { createComment } = useComments()
const { isAuthenticated } = useAuth()

const form = ref({
  content: '',
})

const submitting = ref(false)

const onSubmit = async () => {
  if (!form.value.content.trim()) return

  submitting.value = true
  try {
    await createComment(
      props.articleId,
      form.value.content,
      props.parentId,
    )
    form.value.content = ''
    emit('submitted')
    // TODO: 显示成功提示
  } catch (error) {
    console.error('Failed to submit comment:', error)
    // TODO: 显示错误提示
  } finally {
    submitting.value = false
  }
}
</script>
