<script setup lang="ts">
const props = defineProps<{
  selected: string[]
  search: string
}>()

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

const providerPage = ref(1)
const localSearch = ref(props.search)
const debouncedSearch = refDebounced(localSearch, 300)

watch(() => props.search, (newVal) => {
  localSearch.value = newVal
})

const { data: providersData, pending: providersPending } = useProviders('/providers', {
  query: computed(() => ({
    'page_size': 12,
    'page': providerPage.value,
    ...(debouncedSearch.value && {
      'filters[0][field]': 'search',
      'filters[0][op]': '==',
      'filters[0][value]': debouncedSearch.value
    })
  }))
})

function toggleProvider(providerId: string) {
  const newValue = props.selected.includes(providerId)
    ? props.selected.filter(id => id !== providerId)
    : [...props.selected, providerId]
  emit('update:selected', newValue)
}

function onSearchInput(value: string) {
  localSearch.value = value
  emit('update:search', value)
}
</script>

<template>
  <div class="space-y-4">
    <label class="block text-sm font-medium text-[var(--text-primary)] mb-2">Select Providers</label>
    <p class="text-sm text-[var(--text-muted)] mb-4">Choose insurance providers to get quotes from</p>
    
    <UInput
      :model-value="localSearch"
      @update:model-value="onSearchInput"
      placeholder="Search providers..."
      size="lg"
      icon="i-heroicons-magnifying-glass"
    />
    
    <div v-if="providersPending" class="text-center text-[var(--text-muted)] py-4">
      Loading providers...
    </div>
    
    <div v-else-if="providersData?.data && providersData.data.length > 0" class="space-y-2">
      <div
        v-for="provider in providersData.data"
        :key="provider.provider_id"
        class="flex items-center gap-3 p-4 border border-[var(--card-border)] rounded-lg hover:bg-[var(--card-border)] transition-colors"
      >
        <UCheckbox
          :model-value="selected.includes(provider.provider_id)"
          @update:model-value="toggleProvider(provider.provider_id)"
          size="lg"
        />
        <span class="font-medium text-[var(--text-primary)]">{{ provider.name }}</span>
      </div>
    </div>
    
    <div v-else class="text-center text-[var(--text-muted)] py-4">
      No providers found. Try a different search term.
    </div>
  </div>
</template>
