<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../lib/api.js'

const props = defineProps({ id: { type: String, required: true } })
const tenantId = computed(() => Number(props.id))
const router = useRouter()

const tenant = ref(null)
const agentes = ref([])
const aiConfigs = ref([])
const error = ref('')
const showForm = ref(false)
const editing = ref(null)
const form = ref(vacio())

function vacio() {
  return { nombre: '', ai_config_id: null, tono: '', mensaje_bienvenida: '', color: '#8eb02f', activo: true }
}

async function cargar() {
  error.value = ''
  try {
    const [t, a, ai] = await Promise.all([
      api.get('/app/umind/tenants'),
      api.get(`/app/umind/agentes?tenant_id=${props.id}`),
      api.get('/app/api/ai-config/select'),
    ])
    tenant.value = (t.items || []).find((x) => String(x.ID) === props.id) || null
    agentes.value = a.items || []
    aiConfigs.value = ai.registros || []
  } catch (e) {
    error.value = e.message
  }
}

function nuevoAgente() {
  editing.value = null
  form.value = vacio()
  showForm.value = true
}

function editarAgente(a) {
  editing.value = a
  form.value = {
    nombre: a.nombre,
    ai_config_id: a.ai_config_id,
    tono: a.tono,
    mensaje_bienvenida: a.mensaje_bienvenida,
    color: a.color || '#8eb02f',
    activo: a.activo,
  }
  showForm.value = true
}

async function guardar() {
  try {
    if (editing.value) {
      await api.put(`/app/umind/agentes/${editing.value.ID}`, { tenant_id: tenantId.value, ...form.value })
      showForm.value = false
      await cargar()
    } else {
      const r = await api.post('/app/umind/agentes', { tenant_id: tenantId.value, ...form.value })
      showForm.value = false
      router.push(`/tenants/${tenantId.value}/agentes/${r.id}`)
    }
  } catch (e) {
    error.value = e.message
  }
}

async function eliminarAgente(a) {
  if (!confirm(`¿Eliminar el agente "${a.nombre}"? Esto no se puede deshacer.`)) return
  await api.del(`/app/umind/agentes/${a.ID}`)
  await cargar()
}

onMounted(cargar)
</script>

<template>
  <div>
    <div v-if="tenant" class="mb-6">
      <h1 class="text-xl font-semibold text-gray-800 dark:text-gray-100">{{ tenant.nombre }}</h1>
      <p class="text-xs text-gray-500 dark:text-gray-500 mt-1">{{ tenant.dominios_permitidos || 'sin dominios configurados' }}</p>
    </div>

    <p v-if="error" class="text-sm text-red-600 dark:text-red-400 mb-4">{{ error }}</p>

    <div class="flex items-center justify-between mb-4">
      <h2 class="text-sm font-medium text-gray-600 dark:text-gray-300">Agentes</h2>
      <button class="bg-brand hover:bg-brand-dark text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors" @click="nuevoAgente">
        + Nuevo agente
      </button>
    </div>

    <div class="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 divide-y divide-gray-100 dark:divide-gray-800">
      <div v-if="agentes.length === 0" class="p-6 text-sm text-gray-500 dark:text-gray-400">
        Todavía no hay agentes. Creá el primero.
      </div>
      <div
        v-for="a in agentes"
        :key="a.ID"
        class="group flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-800"
      >
        <router-link :to="`/tenants/${tenantId}/agentes/${a.ID}`" class="flex-1 min-w-0 p-4">
          <div class="font-medium text-gray-800 dark:text-gray-200">{{ a.nombre }}</div>
          <div class="flex items-center gap-1 mt-0.5">
            <span class="w-1.5 h-1.5 rounded-full" :style="{ background: a.activo ? a.color || '#22c55e' : undefined }" :class="!a.activo && 'bg-gray-300 dark:bg-gray-600'"></span>
            <span class="text-xs text-gray-400 dark:text-gray-500">{{ a.activo ? 'activo' : 'inactivo' }}</span>
          </div>
        </router-link>
        <div class="flex items-center gap-3 pr-4 text-sm">
          <router-link :to="`/tenants/${tenantId}/agentes/${a.ID}`" class="text-brand font-medium opacity-0 group-hover:opacity-100 transition-opacity">
            Configurar &rarr;
          </router-link>
          <button class="text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 opacity-0 group-hover:opacity-100 transition-opacity" title="Editar" @click="editarAgente(a)">✎</button>
          <button class="text-gray-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity" title="Eliminar" @click="eliminarAgente(a)">✕</button>
        </div>
      </div>
    </div>

    <div v-if="showForm" class="fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50" @click.self="showForm = false">
      <div class="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl p-6 w-full max-w-lg">
        <h2 class="font-semibold text-gray-800 dark:text-gray-100 mb-4">{{ editing ? 'Editar agente' : 'Nuevo agente' }}</h2>
        <form class="space-y-3" @submit.prevent="guardar">
          <div>
            <label class="text-xs text-gray-500 dark:text-gray-400">Nombre</label>
            <input v-model="form.nombre" required placeholder="ej: Ventas, Soporte" class="w-full border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 rounded-lg px-3 py-2 text-sm" />
          </div>
          <div>
            <label class="text-xs text-gray-500 dark:text-gray-400">Config de IA</label>
            <select v-model="form.ai_config_id" class="w-full border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 rounded-lg px-3 py-2 text-sm">
              <option :value="null">— sin asignar —</option>
              <option v-for="c in aiConfigs" :key="c.ID" :value="c.ID">{{ c.nombre }} ({{ c.provider }})</option>
            </select>
          </div>
          <div>
            <label class="text-xs text-gray-500 dark:text-gray-400">Tono / personalidad</label>
            <textarea v-model="form.tono" rows="2" class="w-full border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 rounded-lg px-3 py-2 text-sm"></textarea>
          </div>
          <div>
            <label class="text-xs text-gray-500 dark:text-gray-400">Mensaje de bienvenida</label>
            <input v-model="form.mensaje_bienvenida" class="w-full border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 rounded-lg px-3 py-2 text-sm" />
          </div>
          <div>
            <label class="text-xs text-gray-500 dark:text-gray-400">Color del widget</label>
            <div class="flex items-center gap-2">
              <input v-model="form.color" type="color" class="w-10 h-9 border border-gray-300 dark:border-gray-700 rounded cursor-pointer bg-white dark:bg-gray-800" />
              <input v-model="form.color" type="text" pattern="#[0-9a-fA-F]{6}" class="flex-1 border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 rounded-lg px-3 py-2 text-sm font-mono" />
            </div>
          </div>
          <label class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
            <input v-model="form.activo" type="checkbox" />
            Activo
          </label>
          <div class="flex justify-end gap-2 pt-2">
            <button type="button" class="px-4 py-2 text-sm text-gray-500 dark:text-gray-400" @click="showForm = false">Cancelar</button>
            <button type="submit" class="bg-brand hover:bg-brand-dark text-white text-sm font-medium px-4 py-2 rounded-lg">
              {{ editing ? 'Guardar' : 'Crear' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
