<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-[var(--wa-text)]">Instancias de WhatsApp</h1>
        <p class="text-[var(--wa-text-muted)]">Gestiona tus conexiones de WhatsApp</p>
      </div>
      <UButton
        icon="i-lucide-plus"
        @click="showCreateModal = true"
      >
        Nueva Instancia
      </UButton>
    </div>

    <!-- Instances Grid -->
    <div v-if="instances.length === 0" class="instance-card p-12 text-center">
      <UIcon name="i-lucide-smartphone" class="w-16 h-16 text-[var(--wa-text-muted)] mx-auto mb-4" />
      <h3 class="text-xl font-semibold text-[var(--wa-text)] mb-2">No hay instancias</h3>
      <p class="text-[var(--wa-text-muted)] mb-6">Crea tu primera instancia para comenzar a usar WhatsApp Nucleo</p>
      <UButton
        icon="i-lucide-plus"
        @click="showCreateModal = true"
      >
        Crear Instancia
      </UButton>
    </div>

    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <InstanceCard
        v-for="instance in instances"
        :key="instance.id"
        :instance="instance"
        @connect="handleConnect"
        @disconnect="handleDisconnect"
        @delete="handleDelete"
      />
    </div>

    <!-- Create Instance Modal -->
    <CreateInstanceModal
      v-model:open="showCreateModal"
      @created="handleCreated"
    />

    <!-- QR Code Modal -->
    <QRCodeModal
      v-model:open="showQRModal"
      :instance-id="selectedInstanceId"
      :qr-code="qrCode"
    />
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'dashboard',
  title: 'Instancias',
  icon: 'i-lucide-smartphone'
})

const showCreateModal = ref(false)
const showQRModal = ref(false)
const selectedInstanceId = ref<string | null>(null)
const qrCode = ref<string | null>(null)

// TODO: Conectar con API real
const instances = ref<any[]>([])

const handleConnect = async (instanceId: string) => {
  selectedInstanceId.value = instanceId
  showQRModal.value = true
  // TODO: Iniciar conexion y obtener QR
}

const handleDisconnect = async (instanceId: string) => {
  // TODO: Desconectar instancia
  console.log('Disconnecting', instanceId)
}

const handleDelete = async (instanceId: string) => {
  // TODO: Eliminar instancia
  console.log('Deleting', instanceId)
}

const handleCreated = (instance: any) => {
  instances.value.push(instance)
  showCreateModal.value = false
}
</script>
