<template>
  <div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
    <h2 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">评论 ({{ commentsList.length }})</h2>
    
    <!-- 评论输入框 -->
    <div class="mb-8">
      <div v-if="isAuthenticated" class="flex items-start space-x-4">
        <div class="flex-shrink-0">
          <img 
            :src="getAssetUrl(user?.avatar || '/src/assets/icons/user.png')" 
            :alt="user?.username"
            class="w-10 h-10 rounded-full object-cover"
          />
        </div>
        <div class="min-w-0 flex-1">
          <div class="border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm overflow-hidden focus-within:border-green-500 focus-within:ring-1 focus-within:ring-green-500">
            <textarea
              rows="3"
              v-model="newComment"
              class="block w-full resize-none border-0 py-3 px-4 focus:ring-0 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              placeholder="写下你的评论..."
            ></textarea>
            <div class="py-2 px-3 bg-gray-50 dark:bg-gray-600 flex items-center justify-between">
              <div class="flex-shrink-0">
                <button
                  type="submit"
                  @click="handleAddComment"
                  :disabled="!newComment.trim() || loading"
                  :class="[
                    'inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm',
                    newComment.trim() && !loading
                      ? 'text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500'
                      : 'text-gray-400 bg-gray-100 dark:bg-gray-500 cursor-not-allowed'
                  ]"
                >
                  <span v-if="loading">发送中...</span>
                  <span v-else>发送</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="text-center py-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
        <p class="text-gray-600 dark:text-gray-300">
          请
          <router-link to="/login" class="text-green-600 dark:text-green-400 hover:text-green-500">登录</router-link>
          后发表评论
        </p>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="loading" class="flex justify-center py-8">
      <LoadingSpinner text="加载中..." />
    </div>
    <template v-else>
      <div class="space-y-6">
        <div v-for="comment in commentsList" :key="comment.id" class="flex space-x-4">
          <div class="flex-shrink-0">
            <img 
              :src="getAssetUrl(comment.author.avatar || '/src/assets/icons/user.png')" 
              :alt="comment.author.username"
              class="w-10 h-10 rounded-full object-cover"
            />
          </div>
          <div class="flex-grow">
            <div class="flex items-center space-x-2">
              <router-link 
                :to="'/profile/' + comment.author.id"
                class="text-sm font-medium text-gray-900 dark:text-white hover:text-green-600"
              >
                {{ comment.author.username }}
              </router-link>
              <span class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(comment.created_at) }}</span>
            </div>
            <div class="mt-1 text-sm text-gray-700 dark:text-gray-300">{{ comment.content }}</div>
            
            <!-- 评论操作 -->
            <div class="mt-2 flex items-center space-x-4 text-sm">
              <button 
                @click="handleDeleteComment(comment.id)"
                v-if="canDelete(comment)"
                class="text-gray-500 dark:text-gray-400 hover:text-red-600"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore" class="mt-6 text-center">
        <button
          @click="loadMore"
          class="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
        >
          加载更多
        </button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuth } from '../composables/useAuth'
import { useComments } from '../composables/useComments'
import LoadingSpinner from './LoadingSpinner.vue'
import { getAssetUrl } from '../utils/assets'

const props = defineProps({
  postId: {
    type: [Number, String],
    required: true
  }
})

const { user, isAuthenticated } = useAuth()
const { 
  commentsList, 
  loading, 
  error,
  fetchComments, 
  addComment, 
  deleteComment 
} = useComments(props.postId)

const newComment = ref('')
const hasMore = ref(false)

const handleAddComment = async () => {
  if (!newComment.value.trim()) return
  
  try {
    await addComment({ content: newComment.value })
    newComment.value = ''
  } catch (err) {
    console.error('Failed to add comment:', err)
  }
}

const handleDeleteComment = async (commentId) => {
  try {
    await deleteComment(commentId)
  } catch (err) {
    console.error('Failed to delete comment:', err)
  }
}

const canDelete = (comment) => {
  return isAuthenticated.value && (
    user.value?.id === comment.author.id || 
    user.value?.is_admin
  )
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadMore = async () => {
  try {
    await fetchComments()
  } catch (err) {
    console.error('Failed to load more comments:', err)
  }
}

onMounted(() => {
  fetchComments()
})
</script>
