<template>
  <div class="link-field">
    <label v-if="label" class="field-label">
      {{ t(label) }}
      <span v-if="required" class="required">*</span>
    </label>
    <div class="link-field-container" ref="containerRef">
      <div class="input-wrapper">
        <n-input
          v-model:value="searchQuery"
          :placeholder="placeholder || t('Search...')"
          @focus="handleFocus"
          @input="handleInput"
          @click="handleInputClick"
          class="link-input"
        />
        <div v-if="hasValue" class="link-buttons">
          <n-button
            size="small"
            quaternary
            @click.stop="clearValue"
            :title="t('Clear')"
            class="action-btn"
          >
            <template #icon>
              <n-icon><Icon icon="mdi:close" /></n-icon>
            </template>
          </n-button>
        </div>
      </div>
      
      <div v-if="showDropdown" class="dropdown-menu">
        <div class="dropdown-content">
          <div v-if="isLoading" class="loading-state">
            {{ t('Loading...') }}
          </div>
          <template v-else>
            <div
              v-for="option in dropdownOptions"
              :key="option.value"
              class="dropdown-item"
              :class="{ 'create-item': option.type === 'create' }"
              @click="handleOptionSelect(option)"
            >
              <Icon v-if="option.type === 'create'" icon="mdi:plus" class="item-icon" />
              <span class="item-label">{{ option.label }}</span>
              <span v-if="option.description" class="item-description">{{ option.description }}</span>
            </div>
            <div v-if="dropdownOptions.length === 0" class="empty-state">
              {{ t('No results found') }}
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { NInput, NButton, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import axios from 'axios'

const props = defineProps<{
  modelValue: string
  options: string  // PageType name, e.g., "Dashboard Chart"
  label?: string
  placeholder?: string
  required?: boolean
  getQuery?: () => any  // Custom query filters
  enableCreate?: boolean  // Enable create new option
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
  'create': []
}>()

const containerRef = ref<HTMLElement | null>(null)
const searchQuery = ref('')
const showDropdown = ref(false)
const isLoading = ref(false)
const dropdownOptions = ref<Array<{ value: string; label: string; description?: string }>>([])

const hasValue = computed(() => !!props.modelValue)

// Initialize display value from modelValue
watch(() => props.modelValue, (newVal) => {
  if (newVal && !searchQuery.value) {
    searchQuery.value = newVal
  }
}, { immediate: true })

async function searchOptions(query: string = '') {
  if (!props.options) return
  
  isLoading.value = true
  
  try {
    const customQuery = props.getQuery?.() || {}
    
    const response = await axios.post('/api/action/jingrow.desk.search.search_link', {
      pagetype: props.options,
      txt: query || '',
      page_length: 20,
      ...customQuery
    })
    
    if (response.data?.message) {
      const results = response.data.message
      const normalOptions = results
        .filter((item: any) => item.value && !item.value.includes('__link_option'))
        .map((item: any) => ({
          value: item.value,
          label: item.label || item.value,
          description: item.description
        }))
      
      // Add "Create new..." option at the end if enabled
      if (props.enableCreate !== false) {
        dropdownOptions.value = [
          ...normalOptions,
          {
            value: '__create_new__',
            label: t('Create a new {0}', [t(props.options)]),
            type: 'create'
          }
        ]
      } else {
        dropdownOptions.value = normalOptions
      }
    } else {
      dropdownOptions.value = []
    }
  } catch (error) {
    console.error('Search link error:', error)
    dropdownOptions.value = []
  } finally {
    isLoading.value = false
  }
}

function handleFocus() {
  if (!showDropdown.value) {
    showDropdown.value = true
    searchOptions(searchQuery.value)
  }
}

function handleInputClick() {
  if (!showDropdown.value) {
    showDropdown.value = true
    searchOptions(searchQuery.value)
  }
}

function handleInput(value: string) {
  searchQuery.value = value
  searchOptions(value)
}

function handleOptionSelect(option: any) {
  if (option.type === 'create') {
    // Emit create event to parent
    showDropdown.value = false
    emit('create')
    return
  }
  
  searchQuery.value = option.label
  emit('update:modelValue', option.value)
  showDropdown.value = false
}

function clearValue() {
  searchQuery.value = ''
  emit('update:modelValue', '')
}

function handleClickOutside(event: Event) {
  if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
    showDropdown.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.link-field {
  margin-bottom: 16px;
}

.field-label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #e03131;
  margin-left: 2px;
}

.link-field-container {
  position: relative;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.link-input {
  flex: 1;
}

.link-buttons {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 4px;
  background: white;
  padding: 2px;
  border-radius: 4px;
}

.action-btn {
  width: 24px;
  height: 24px;
  min-width: 24px;
  padding: 0;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9999;
  margin-top: 4px;
}

.dropdown-content {
  background: white;
  border: 1px solid #e0e0e6;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: 240px;
  overflow-y: auto;
}

.dropdown-item {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.item-label {
  display: block;
  font-size: 14px;
  color: #333;
}

.item-description {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.empty-state,
.loading-state {
  padding: 16px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.dropdown-item.create-item {
  color: #18a058;
  font-weight: 500;
}

.item-icon {
  color: #18a058;
  font-size: 16px;
  flex-shrink: 0;
}
</style>
