<template>
  <div class="relative group/input" ref="containerRef">
    <input 
      :name="name" 
      type="text" 
      :class="inputClass"
      :placeholder="inputPlaceholder"
      :value="modelValue"
      :required="required"
      @input="handleInput"
      @focus="showDropdown = true"
      @blur="handleBlur"
      autocomplete="off"
    >
    <label 
      v-if="variant === 'inquiry'"
      class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all pointer-events-none peer-focus:-top-4 peer-focus:text-art-accent peer-[:not(:placeholder-shown)]:-top-4 peer-[:not(:placeholder-shown)]:text-white/50 peer-autofill:-top-4 peer-autofill:text-white/50"
    >{{ label }}</label>

    <!-- Autocomplete Dropdown -->
    <div v-if="showDropdown && (suggestions.length > 0 || matchedUsers.length > 0)" class="absolute z-[9999] left-0 right-0 top-full mt-1 bg-[#1a1a1a] border border-white/10 shadow-lg max-h-48 overflow-y-auto rounded-b-md">
      <div v-if="matchedUsers.length > 0" class="border-b border-white/5">
        <div class="px-3 py-1.5 text-[10px] text-art-muted uppercase tracking-wider">已注册用户</div>
        <div
          v-for="user in matchedUsers"
          :key="user.id"
          class="px-4 py-2 text-sm text-white/70 hover:bg-art-accent hover:text-black cursor-pointer transition-colors flex items-center gap-2"
          @mousedown.prevent="selectUser(user)"
        >
          <div class="w-6 h-6 rounded-full overflow-hidden bg-white/10 shrink-0 flex items-center justify-center text-xs text-art-accent">
            <img v-if="user.avatar" :src="user.avatar" :alt="user.username" class="w-full h-full object-cover" />
            <span v-else>{{ user.username.charAt(0).toUpperCase() }}</span>
          </div>
          <div class="min-w-0">
            <div class="truncate font-medium">{{ user.username }}</div>
            <div class="truncate text-xs opacity-70">{{ user.email }}</div>
          </div>
        </div>
      </div>
      <div 
        v-for="(suggestion, index) in suggestions" 
        :key="'s-' + index"
        class="px-4 py-2 text-sm text-white/70 hover:bg-art-accent hover:text-black cursor-pointer transition-colors font-mono"
        @mousedown.prevent="selectSuggestion(suggestion)"
      >
        {{ suggestion }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { fetchEmailSuffixes, getUsersPaginated, type User } from '../../services/api'
import { useUserProfileModal } from '../../composables/useUserProfileModal'

const props = withDefaults(defineProps<{
  name: string
  label: string
  placeholder?: string
  modelValue: string
  required?: boolean
  userLookup?: boolean
  variant?: 'inquiry' | 'admin'
}>(), {
  userLookup: false,
  variant: 'inquiry',
})

const emit = defineEmits(['update:modelValue', 'user-select'])

const { openUserProfile } = useUserProfileModal()

const inputPlaceholder = computed(() => props.placeholder ?? (props.variant === 'inquiry' ? ' ' : ''))

const inputClass = computed(() => {
  if (props.variant === 'admin') {
    return 'admin-input w-full peer'
  }
  return 'inquiry-input peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent'
})

const showDropdown = ref(false)
const emailSuffixes = ref<string[]>([])
const matchedUsers = ref<User[]>([])
const containerRef = ref<HTMLElement | null>(null)
let userSearchTimer: ReturnType<typeof setTimeout> | null = null

onMounted(async () => {
  try {
    const suffixes = await fetchEmailSuffixes()
    emailSuffixes.value = suffixes.map(s => s.suffix)
  } catch {
    emailSuffixes.value = ['@gmail.com', '@163.com', '@qq.com', '@outlook.com']
  }
})

const searchUsers = (keyword: string) => {
  if (!props.userLookup || !keyword.includes('@') || keyword.length < 3) {
    matchedUsers.value = []
    return
  }
  if (userSearchTimer) clearTimeout(userSearchTimer)
  userSearchTimer = setTimeout(async () => {
    try {
      const result = await getUsersPaginated({ page: 1, pageSize: 5, keyword })
      matchedUsers.value = result.list
    } catch {
      matchedUsers.value = []
    }
  }, 300)
}

const handleInput = (e: Event) => {
  const val = (e.target as HTMLInputElement).value
  emit('update:modelValue', val)
  showDropdown.value = true
  searchUsers(val)
}

const handleBlur = () => {
  setTimeout(() => {
    showDropdown.value = false
  }, 200)
}

const suggestions = computed(() => {
  if (!props.modelValue || props.modelValue.includes('@')) return []
  return emailSuffixes.value.map(suffix => `${props.modelValue}${suffix}`)
})

const selectSuggestion = (val: string) => {
  emit('update:modelValue', val)
  showDropdown.value = false
}

const selectUser = (user: User) => {
  emit('user-select', user)
  openUserProfile(user.id)
  showDropdown.value = false
}
</script>

<style scoped>
.inquiry-input:-webkit-autofill,
.inquiry-input:-webkit-autofill:hover,
.inquiry-input:-webkit-autofill:focus,
.inquiry-input:-webkit-autofill:active {
  -webkit-box-shadow: 0 0 0 1000px #080808 inset !important;
  -webkit-text-fill-color: white !important;
  caret-color: white;
  transition: background-color 5000s ease-in-out 0s;
}
</style>
