<template>
  <div class="vlog-comments">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-lg font-semibold text-gray-900">
        Commentaires ({{ comments.length }})
      </h3>
      <button
        @click="showCommentForm = !showCommentForm"
        class="btn-primary text-sm"
      >
        <MessageSquare class="w-4 h-4 mr-2" />
        {{ showCommentForm ? 'Annuler' : 'Commenter' }}
      </button>
    </div>
    
    <!-- Comment Form -->
    <div v-if="showCommentForm" class="mb-6">
      <form @submit.prevent="submitComment" class="space-y-3">
                      <MentionInput
                v-model="newComment"
                :users="commentUsers"
                :rows="3"
                placeholder="Écrivez votre commentaire... (utilisez @username pour mentionner)"
                @mentions-changed="handleCommentMentionsChanged"
              />
        <div class="flex items-center justify-between">
          <span class="text-sm text-gray-500">
            {{ newComment.length }}/1000 caractères
          </span>
          <button
            type="submit"
            :disabled="!newComment.trim() || submitting"
            class="btn-primary text-sm"
          >
            {{ submitting ? 'Envoi...' : 'Envoyer' }}
          </button>
        </div>
      </form>
    </div>
    
    <!-- Comments List -->
    <div v-if="comments.length === 0" class="text-center py-8 text-gray-500">
      <MessageSquare class="w-16 h-16 mx-auto mb-4 text-gray-300" />
      <h4 class="text-lg font-medium mb-2">Aucun commentaire</h4>
      <p>Soyez le premier à commenter ce vlog !</p>
    </div>
    
    <div v-else class="space-y-4">
      <div
        v-for="comment in comments"
        :key="comment.id"
        class="flex space-x-3 p-4 bg-gray-50 rounded-lg"
      >
        <!-- User Avatar -->
        <div class="flex-shrink-0">
          <img
            v-if="comment.avatar_url"
            :src="getAvatarUrl(comment.avatar_url)"
            :alt="comment.full_name"
            class="w-10 h-10 rounded-full object-cover"
          >
          <div v-else class="w-10 h-10 rounded-full bg-primary-100 flex items-center justify-center">
            <User class="w-5 h-5 text-primary-600" />
          </div>
        </div>
        
        <!-- Comment Content -->
        <div class="flex-1 min-w-0">
          <div class="flex items-center space-x-2 mb-1">
            <span class="font-medium text-gray-900">{{ comment.full_name }}</span>
            <span class="text-sm text-gray-500">@{{ comment.username }}</span>
            <span class="text-xs text-gray-400">{{ formatDate(comment.created_at) }}</span>
          </div>
          
          <Mentions :content="comment.content" :mentions="comment.mentioned_users || []" class="text-gray-700 whitespace-pre-wrap" />
          
          <!-- Comment Actions -->
          <div class="flex items-center space-x-4 mt-2">
            <button
              v-if="canDeleteComment(comment)"
              @click="deleteComment(comment.id)"
              class="text-xs text-red-600 hover:text-red-800 transition-colors"
            >
              Supprimer
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useToast } from 'vue-toastification'
import { MessageSquare, User } from 'lucide-vue-next'
import Mentions from '@/components/Mentions.vue'
import MentionInput from '@/components/MentionInput.vue'
import { formatDistanceToNow } from 'date-fns'
import { fr } from 'date-fns/locale'
import { getMediaUrl } from '@/utils/axios'
import axios from '@/utils/axios'

const props = defineProps({
  vlogId: {
    type: Number,
    required: true
  },
  comments: {
    type: Array,
    default: () => []
  },
  commentUsers: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['comment-added', 'comment-deleted'])

const authStore = useAuthStore()
const toast = useToast()

const showCommentForm = ref(false)
const newComment = ref('')
const submitting = ref(false)
const commentMentions = ref([])

const currentUser = computed(() => authStore.user)

function formatDate(date) {
  return formatDistanceToNow(new Date(date), { addSuffix: true, locale: fr })
}

function getAvatarUrl(avatarUrl) {
  return getMediaUrl(avatarUrl)
}

function canDeleteComment(comment) {
  return currentUser.value && (
    comment.user_id === currentUser.value.id || 
    currentUser.value.is_admin
  )
}

function handleCommentMentionsChanged(mentions) {
  commentMentions.value = mentions
}

async function submitComment() {
  if (!newComment.value.trim()) return
  
  submitting.value = true
  try {
    const response = await axios.post(`/api/vlogs/${props.vlogId}/comment`, { content: newComment.value.trim() })
    
    if (response.data) {
      emit('comment-added', response.data.comment)
      newComment.value = ''
      showCommentForm.value = false
      toast.success('Commentaire ajouté')
    } else {
      throw new Error('Erreur lors de l\'ajout du commentaire')
    }
  } catch (error) {
    toast.error('Erreur lors de l\'ajout du commentaire')
    console.error('Error adding comment:', error)
  } finally {
    submitting.value = false
  }
}

async function deleteComment(commentId) {
  if (!confirm('Êtes-vous sûr de vouloir supprimer ce commentaire ?')) return
  
  try {
    const response = await axios.delete(`/api/vlogs/${props.vlogId}/comment/${commentId}`)
    
    if (response.data) {
      emit('comment-deleted', commentId)
      toast.success('Commentaire supprimé')
    } else {
      throw new Error('Erreur lors de la suppression')
    }
  } catch (error) {
    toast.error('Erreur lors de la suppression du commentaire')
    console.error('Error deleting comment:', error)
  }
}
</script>