<template>
  <div class="mention-input-container">
    <textarea
      ref="textareaRef"
      v-model="inputValue"
      :placeholder="placeholder"
      :rows="rows"
      :class="inputClass"
      @input="handleInput"
      @keydown="handleKeydown"
      @focus="showSuggestions = true"
      @blur="handleBlur"
    />
    
    <!-- Suggestions de mentions -->
    <div
      v-if="showSuggestions && filteredUsers.length > 0"
      class="mention-suggestions"
    >
      <div
        v-for="(user, index) in filteredUsers"
        :key="user.id"
        :class="[
          'mention-suggestion-item',
          { 'selected': index === selectedIndex }
        ]"
        @click="selectUser(user)"
        @mouseenter="selectedIndex = index"
      >
        <img
          v-if="user.avatar_url"
          :src="getMediaUrl(user.avatar_url)"
          :alt="user.full_name"
          class="w-6 h-6 rounded-full mr-2"
        >
        <div v-else class="w-6 h-6 rounded-full bg-primary-100 flex items-center justify-center mr-2">
          <User class="w-3 h-3 text-primary-600" />
        </div>
        <div>
          <div class="font-medium text-sm">{{ user.full_name }}</div>
          <div class="text-xs text-gray-500">@{{ user.username }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { User } from 'lucide-vue-next'
import { getMediaUrl } from '@/utils/axios'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: 'Écrivez votre message...'
  },
  rows: {
    type: Number,
    default: 3
  },
  inputClass: {
    type: String,
    default: 'input resize-none'
  },
  users: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'mentions-changed'])

const textareaRef = ref(null)
const inputValue = ref(props.modelValue)
const showSuggestions = ref(false)
const selectedIndex = ref(0)
const currentMentionStart = ref(-1)
const currentMentionQuery = ref('')

// Synchroniser avec la valeur externe
watch(() => props.modelValue, (newValue) => {
  inputValue.value = newValue
})

watch(inputValue, (newValue) => {
  emit('update:modelValue', newValue)
  updateMentions()
})

const filteredUsers = computed(() => {
  if (!currentMentionQuery.value) return []
  
  return props.users.filter(user => 
    user.username.toLowerCase().includes(currentMentionQuery.value.toLowerCase()) ||
    user.full_name.toLowerCase().includes(currentMentionQuery.value.toLowerCase())
  ).slice(0, 5)
})

function handleInput() {
  const text = inputValue.value
  const cursorPos = textareaRef.value.selectionStart
  
  // Chercher la mention en cours
  const beforeCursor = text.substring(0, cursorPos)
  const mentionMatch = beforeCursor.match(/@(\w*)$/)
  
  if (mentionMatch) {
    currentMentionStart.value = mentionMatch.index
    currentMentionQuery.value = mentionMatch[1]
    showSuggestions.value = true
    selectedIndex.value = 0
  } else {
    showSuggestions.value = false
    currentMentionStart.value = -1
    currentMentionQuery.value = ''
  }
}

function handleKeydown(event) {
  if (!showSuggestions.value) return
  
  if (event.key === 'ArrowDown') {
    event.preventDefault()
    selectedIndex.value = Math.min(selectedIndex.value + 1, filteredUsers.value.length - 1)
  } else if (event.key === 'ArrowUp') {
    event.preventDefault()
    selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
  } else if (event.key === 'Enter' && filteredUsers.value.length > 0) {
    event.preventDefault()
    selectUser(filteredUsers.value[selectedIndex.value])
  } else if (event.key === 'Escape') {
    showSuggestions.value = false
  }
}

function selectUser(user) {
  if (currentMentionStart.value === -1) return
  
  const beforeMention = inputValue.value.substring(0, currentMentionStart.value)
  const afterMention = inputValue.value.substring(currentMentionStart.value + currentMentionQuery.value.length + 1)
  
  inputValue.value = beforeMention + '@' + user.username + ' ' + afterMention
  
  // Positionner le curseur après la mention
  nextTick(() => {
    const newCursorPos = currentMentionStart.value + user.username.length + 2
    textareaRef.value.setSelectionRange(newCursorPos, newCursorPos)
    textareaRef.value.focus()
  })
  
  showSuggestions.value = false
  currentMentionStart.value = -1
  currentMentionQuery.value = ''
}

function handleBlur() {
  // Délai pour permettre le clic sur les suggestions
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}

function updateMentions() {
  const mentions = []
  const mentionRegex = /@(\w+)/g
  let match
  
  while ((match = mentionRegex.exec(inputValue.value)) !== null) {
    const username = match[1]
    const user = props.users.find(u => u.username === username)
    if (user) {
      mentions.push({
        id: user.id,
        username: user.username,
        full_name: user.full_name
      })
    }
  }
  
  emit('mentions-changed', mentions)
}
</script>

<style scoped>
.mention-input-container {
  position: relative;
}

.mention-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  z-index: 50;
  max-height: 200px;
  overflow-y: auto;
}

.mention-suggestion-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  cursor: pointer;
  transition: background-color 0.15s;
}

.mention-suggestion-item:hover,
.mention-suggestion-item.selected {
  background-color: #f3f4f6;
}

.mention-suggestion-item:first-child {
  border-top-left-radius: 0.5rem;
  border-top-right-radius: 0.5rem;
}

.mention-suggestion-item:last-child {
  border-bottom-left-radius: 0.5rem;
  border-bottom-right-radius: 0.5rem;
}
</style>
