<template>
  <div class="relative">
    <input
      v-model="query"
      @input="onInput"
      @focus="showDropdown = true"
      class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
      placeholder="Введите название организации или ИНН..."
      autocomplete="off"
    />
    
    <!-- Dropdown with suggestions -->
    <div 
      v-if="showDropdown && suggestions.length > 0" 
      class="absolute top-full left-0 right-0 z-50 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto"
    >
      <div
        v-for="(suggestion, index) in suggestions"
        :key="index"
        @click="selectCompany(suggestion)"
        class="p-3 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0"
      >
        <div class="font-medium text-gray-900">{{ suggestion.value }}</div>
        <div class="text-sm text-gray-600">
          ИНН: {{ suggestion.data.inn }}
          <span v-if="suggestion.data.kpp"> • КПП: {{ suggestion.data.kpp }}</span>
        </div>
        <div v-if="suggestion.data.address" class="text-xs text-gray-500 mt-1">
          {{ suggestion.data.address.value }}
        </div>
      </div>
    </div>
    
    <!-- Loading indicator -->
    <div v-if="loading" class="absolute right-3 top-1/2 -translate-y-1/2">
      <div class="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
interface CompanyData {
  companyName: string
  companyFullName: string
  inn: string
  kpp: string
  ogrn: string
  address: string
}

interface Props {
  modelValue?: CompanyData
}

interface Emits {
  (e: 'update:modelValue', value: CompanyData): void
  (e: 'select', company: any): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({
    companyName: '',
    companyFullName: '',
    inn: '',
    kpp: '',
    ogrn: '',
    address: ''
  })
})

const emit = defineEmits<Emits>()

const query = ref('')
const suggestions = ref([])
const loading = ref(false)
const showDropdown = ref(false)

// Hide dropdown when clicking outside
onMounted(() => {
  document.addEventListener('click', (e) => {
    if (!e.target?.closest('.relative')) {
      showDropdown.value = false
    }
  })
})

const onInput = async () => {
  if (query.value.length < 2) {
    suggestions.value = []
    showDropdown.value = false
    return
  }
  
  loading.value = true
  try {
    const response = await fetch('https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/party', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Token 8de30547fe1e228dd5d7289439b71f5a97cf7357'
      },
      body: JSON.stringify({
        query: query.value,
        count: 10
      })
    })
    
    const data = await response.json()
    suggestions.value = data.suggestions || []
    showDropdown.value = true
    
  } catch (error) {
    console.error('DADATA error:', error)
    suggestions.value = []
  } finally {
    loading.value = false
  }
}

const selectCompany = (company: any) => {
  query.value = company.value
  showDropdown.value = false
  
  const companyData: CompanyData = {
    companyName: company.value,
    companyFullName: company.unrestricted_value,
    inn: company.data.inn,
    kpp: company.data.kpp || '',
    ogrn: company.data.ogrn || '',
    address: company.data.address?.value || ''
  }
  
  emit('update:modelValue', companyData)
  emit('select', company)
}
</script>