<div x-data="notifConfig()" x-init="init()" class="p-6">

  <div class="mb-6">
    <h1 class="text-xl font-bold text-slate-800">Configuración de notificaciones</h1>
    <p class="text-sm text-slate-500 mt-0.5">
      Define por qué canales se envían las alertas a cada destinatario. Más eventos se agregarán conforme el sistema crezca.
    </p>
  </div>

  <!-- Tabla de configuración -->
  <div class="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
    <table class="w-full text-sm">
      <thead>
        <tr class="bg-slate-50 border-b border-slate-200">
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-48">Evento</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-40">Destinatario</th>
          <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
            📧 Email
          </th>
          <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
            ✈️ Telegram
          </th>
          <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
            🔔 Sistema
          </th>
          <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Guardar</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        <template x-for="row in rows" :key="row.key">
          <tr class="hover:bg-slate-50 transition-colors">
            <td class="px-4 py-3">
              <span class="font-medium text-slate-700" x-text="row.eventoLabel"></span>
            </td>
            <td class="px-4 py-3">
              <span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium"
                :class="row.destinatario==='admin' ? 'bg-slate-100 text-slate-700' : 'bg-emerald-50 text-emerald-700'">
                <span x-text="row.destinatario==='admin' ? '👤 Admin' : '🧑‍💼 Cliente portal'"></span>
              </span>
            </td>
            <!-- Email -->
            <td class="px-4 py-3 text-center">
              <label class="inline-flex items-center justify-center cursor-pointer">
                <input type="checkbox" x-model="row.canal_email"
                  class="w-4 h-4 rounded accent-[#8eb02f]">
              </label>
            </td>
            <!-- Telegram -->
            <td class="px-4 py-3 text-center">
              <div class="flex flex-col items-center gap-1">
                <label class="inline-flex items-center justify-center cursor-pointer">
                  <input type="checkbox" x-model="row.canal_telegram"
                    :disabled="row.destinatario==='portal_user' ? false : !hasTelegramConfig"
                    class="w-4 h-4 rounded accent-[#8eb02f] disabled:opacity-40">
                </label>
                <span x-show="row.destinatario==='admin' && !hasTelegramConfig"
                  class="text-xs text-amber-500">Sin bot config.</span>
                <span x-show="row.destinatario==='portal_user'"
                  class="text-xs text-slate-400">Requiere Chat ID en usuario</span>
              </div>
            </td>
            <!-- Sistema -->
            <td class="px-4 py-3 text-center">
              <label class="inline-flex items-center justify-center cursor-pointer">
                <input type="checkbox" x-model="row.canal_sistema"
                  class="w-4 h-4 rounded accent-[#8eb02f]">
              </label>
            </td>
            <!-- Guardar -->
            <td class="px-4 py-3 text-center">
              <button @click="save(row)"
                class="px-3 py-1.5 rounded-lg text-white text-xs font-medium transition-colors"
                style="background:#8eb02f"
                onmouseover="this.style.background='#6d8c24'" onmouseout="this.style.background='#8eb02f'">
                Guardar
              </button>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <!-- Ayuda: Telegram para portal users -->
  <div class="mt-6 bg-blue-50 border border-blue-200 rounded-xl p-4 text-sm text-blue-800">
    <p class="font-semibold mb-1">📱 Telegram para clientes del portal</p>
    <p class="text-blue-700 text-xs leading-relaxed">
      Para notificar a un cliente por Telegram, el cliente debe abrir una conversación con el bot y compartirte su <strong>Chat ID</strong>.
      Luego ve a <a href="/app/portal-usuarios" class="underline font-medium">Portal Usuarios</a> y agrega el Chat ID en su perfil.
      El bot a usar es el mismo configurado en <a href="/app/telegram" class="underline font-medium">Configuración Telegram</a>.
    </p>
  </div>

  <!-- ── Umbrales de alerta de servidores ─────────────────────────────── -->
  <div class="mt-8" x-data="servidorUmbralConfig()">
    <div class="flex items-center justify-between mb-3">
      <h2 class="text-base font-bold text-slate-700">🖥️ Umbrales de alerta de servidores</h2>
      <label class="flex items-center gap-2 cursor-pointer">
        <span class="text-sm text-slate-600">Activo</span>
        <input type="checkbox" x-model="form.activo" class="w-4 h-4 rounded accent-[#8eb02f]">
      </label>
    </div>

    <div class="bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm">
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-0 divide-y sm:divide-y-0 sm:divide-x divide-slate-100">

        <!-- Minutos sin ping -->
        <div class="p-4">
          <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">⏱ Sin señal (minutos)</label>
          <p class="text-xs text-slate-400 mb-2">Alerta si el agente no reporta en X minutos.</p>
          <input type="number" min="1" max="120" x-model.number="form.minutos_sin_ping"
            class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
        </div>

        <!-- Umbral CPU -->
        <div class="p-4">
          <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">🔥 Umbral CPU (%)</label>
          <p class="text-xs text-slate-400 mb-2">Alerta si la CPU supera este porcentaje.</p>
          <input type="number" min="50" max="100" x-model.number="form.umbral_cpu"
            class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
        </div>

        <!-- Umbral RAM -->
        <div class="p-4">
          <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">🧠 Umbral RAM (%)</label>
          <p class="text-xs text-slate-400 mb-2">Alerta si la RAM supera este porcentaje.</p>
          <input type="number" min="50" max="100" x-model.number="form.umbral_ram"
            class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
        </div>

        <!-- Umbral Disco -->
        <div class="p-4">
          <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">💾 Umbral Disco (%)</label>
          <p class="text-xs text-slate-400 mb-2">Alerta si el disco supera este porcentaje.</p>
          <input type="number" min="50" max="100" x-model.number="form.umbral_disco"
            class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
        </div>

        <!-- Días antes de vencimiento -->
        <div class="p-4">
          <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">📅 Avisar antes de vencer (días)</label>
          <p class="text-xs text-slate-400 mb-2">Alerta X días antes de que venza el VPS.</p>
          <input type="number" min="1" max="60" x-model.number="form.dias_ante_vencimiento"
            class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
        </div>

        <!-- Guardar -->
        <div class="p-4 flex items-end">
          <button @click="guardar()"
            class="w-full px-4 py-2 rounded-lg text-white text-sm font-medium transition-colors"
            style="background:#8eb02f"
            onmouseover="this.style.background='#6d8c24'" onmouseout="this.style.background='#8eb02f'">
            Guardar umbrales
          </button>
        </div>

      </div>
    </div>

    <!-- Feedback -->
    <div x-show="umbralToast.visible" x-transition
      class="fixed bottom-6 left-6 z-50 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium"
      :class="umbralToast.ok ? 'bg-green-600' : 'bg-red-500'"
      x-text="umbralToast.msg">
    </div>
  </div>

  <!-- Toast (eventos) -->
  <div x-show="toast.visible" x-transition
    class="fixed bottom-6 right-6 z-50 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium"
    :class="toast.ok ? 'bg-green-600' : 'bg-red-500'"
    x-text="toast.msg">
  </div>

</div>

<script>
// Definición de todos los eventos configurables (extensible)
const EVENTOS = [
  { evento: 'ticket_nuevo',             destinatario: 'admin',       label: 'Ticket nuevo',              icon: '🎫' },
  { evento: 'ticket_respuesta_cliente', destinatario: 'admin',       label: 'Respuesta del cliente',     icon: '💬' },
  { evento: 'ticket_respuesta_admin',   destinatario: 'portal_user', label: 'Respuesta del admin',       icon: '💬' },
  { evento: 'factura_subida',           destinatario: 'portal_user', label: 'Factura subida / disponible', icon: '🧾' },
  // Servidores
  { evento: 'servidor_caido',           destinatario: 'admin',       label: 'Servidor sin señal (agente caído)', icon: '🔴' },
  { evento: 'servidor_vence_pronto',    destinatario: 'admin',       label: 'VPS próximo a vencer',      icon: '📅' },
  { evento: 'servidor_recurso_alto',    destinatario: 'admin',       label: 'Recurso al límite (CPU/RAM/Disco)', icon: '⚠️' },
  // Tareas
  { evento: 'tarea_asignada',           destinatario: 'admin',       label: 'Tarea asignada',            icon: '📋' },
  { evento: 'tarea_estado',             destinatario: 'admin',       label: 'Tarea cambio de estado',    icon: '🔀' },
  { evento: 'tarea_comentario',         destinatario: 'admin',       label: 'Comentario en tarea',       icon: '💬' },
];

function notifConfig() {
  return {
    rows: [],
    hasTelegramConfig: false,
    toast: { visible: false, ok: true, msg: '' },

    async init() {
      // Verificar si hay telegram configurado (la API devuelve array directo)
      try {
        const t = await axios.get('/app/loadtelegram');
        this.hasTelegramConfig = Array.isArray(t.data) && t.data.some(b => b.activo);
      } catch {}

      // Cargar configuración existente
      let existing = {};
      try {
        const r = await axios.get('/app/notif-config/data');
        (r.data || []).forEach(cfg => { existing[`${cfg.evento}__${cfg.destinatario}`] = cfg; });
      } catch {}

      // Construir filas combinando EVENTOS con config guardada
      this.rows = EVENTOS.map(ev => {
        const key = `${ev.evento}__${ev.destinatario}`;
        const saved = existing[key] || {};
        return {
          key,
          evento: ev.evento,
          destinatario: ev.destinatario,
          eventoLabel: `${ev.icon} ${ev.label}`,
          canal_email:    saved.canal_email    ?? (ev.destinatario === 'admin'),
          canal_telegram: saved.canal_telegram ?? false,
          canal_sistema:  saved.canal_sistema  ?? true,
        };
      });
    },

    async save(row) {
      try {
        await axios.post('/app/notif-config', {
          evento:         row.evento,
          destinatario:   row.destinatario,
          canal_email:    row.canal_email,
          canal_telegram: row.canal_telegram,
          canal_sistema:  row.canal_sistema,
        });
        this.showToast('Configuración guardada', true);
      } catch (e) {
        this.showToast('Error al guardar', false);
      }
    },

    showToast(msg, ok) {
      this.toast = { visible: true, ok, msg };
      setTimeout(() => this.toast.visible = false, 3000);
    },
  };
}

function servidorUmbralConfig() {
  return {
    form: { activo: true, minutos_sin_ping: 10, umbral_cpu: 90, umbral_ram: 90, umbral_disco: 90, dias_ante_vencimiento: 7 },
    umbralToast: { visible: false, ok: true, msg: '' },
    async init() {
      try {
        const r = await axios.get('/app/servidor-alerta-config');
        if (r.data?.data) this.form = r.data.data;
      } catch {}
    },
    async guardar() {
      try {
        await axios.post('/app/servidor-alerta-config', this.form);
        this.umbralToast = { visible: true, ok: true, msg: 'Umbrales guardados' };
      } catch {
        this.umbralToast = { visible: true, ok: false, msg: 'Error al guardar' };
      }
      setTimeout(() => this.umbralToast.visible = false, 3000);
    },
  };
}
</script>
