<template>
  <div class="relative">
    <input
      v-model="searchQuery"
      @input="debouncedSearch"
      type="text"
      class="form-input"
      placeholder="Search by MRN or patient name..."
    />
    <ul
      v-if="results.length > 0"
      class="absolute z-10 w-full bg-white border border-gray-200 rounded-md
             shadow-lg mt-2 max-h-48 overflow-y-auto"
    >
      <li
        v-for="patient in results"
        :key="patient.id"
        @click="selectPatient(patient)"
        class="px-4 py-2 hover:bg-primary-50 cursor-pointer text-sm"
      >
        <span class="font-medium">{{ patient.fullName }}</span>
        <span class="text-gray-500 ml-2">MRN: {{ patient.mrn }}</span>
      </li>
    </ul>
    <p v-if="selectedPatient" class="text-sm text-clinical-safe mt-2">
      Selected: {{ selectedPatient.fullName }}
    </p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { get } from '../api/client'
import type { PatientSearchResult } from '../types'

const emit = defineEmits<{ (e: 'update:modelValue', value: string | undefined): void }>()

const searchQuery = ref('')
const results = ref<PatientSearchResult[]>([])
const selectedPatient = ref<PatientSearchResult | null>(null)
let debounceTimer: ReturnType<typeof setTimeout>

function debouncedSearch() {
  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(search, 300)
}

async function search() {
  if (searchQuery.value.length < 2) {
    results.value = []
    return
  }
  try {
    const response = await get<PatientSearchResult[]>('patients/search', {
      q: searchQuery.value,
    })
    if (response.success && response.data) {
      results.value = response.data
    }
  } catch {
    results.value = []
  }
}

function selectPatient(patient: PatientSearchResult) {
  selectedPatient.value = patient
  searchQuery.value = patient.fullName
  results.value = []
  emit('update:modelValue', patient.id)
}
</script>
