<template>
  <div class="flex flex-col md:flex-row gap-4">
    <!-- Selector de clientes -->
    <div class="flex-1">
      <label class="text-xs text-[var(--brand-text-muted)] block mb-1">Seleccionar clientes</label>
      <USelectMenu
        v-model="selectedClientes"
        :options="clienteOptions"
        multiple
        searchable
        searchable-placeholder="Buscar cliente..."
        placeholder="Todos los clientes"
        value-attribute="id"
        option-attribute="name"
        :ui="{
          wrapper: 'w-full',
          input: 'w-full'
        }"
      >
        <template #label>
          <span v-if="selectedClientes.length === 0">Todos los clientes</span>
          <span v-else-if="selectedClientes.length === 1">
            {{ clienteOptions.find(c => c.id === selectedClientes[0])?.name }}
          </span>
          <span v-else>
            {{ selectedClientes.length }} clientes seleccionados
          </span>
        </template>
      </USelectMenu>
    </div>

    <div class="flex items-end">
      <UButton
        :ui="{ base: 'bg-[#c08040] text-[#1b1209] border border-[#d99a56] hover:bg-[#d99a56] hover:border-[#f0c07c]' }"
        @click="clearSelection"
        size="sm"
      >
        Limpiar
      </UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'

interface Cliente {
  id: number
  name: string
  cedula?: number
  ubicacion?: string
  telefono?: string
}

interface Props {
  clientes: Cliente[]
  selectedIds: number[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:selectedIds': [value: number[]]
}>()

// Reactive reference para el v-model
const selectedClientes = computed({
  get: () => props.selectedIds,
  set: (value) => emit('update:selectedIds', value)
})

const clienteOptions = computed(() => {
  return props.clientes
    .filter(c => c.name && c.name.trim() !== '')
    .sort((a, b) => a.name.localeCompare(b.name))
})

function clearSelection() {
  emit('update:selectedIds', [])
  console.log('Cliente selection cleared')
}

// Watch para logging
watch(() => props.selectedIds, (newIds) => {
  console.log('Selected cliente IDs:', newIds)
}, { deep: true })
</script>
