<script setup>
import AppLayout from '@/Layouts/AppLayout.vue';
import { ref, computed } from 'vue';
import { useForm, router, Head } from '@inertiajs/vue3';

const props = defineProps({
  title: String,
  personal: { type: Array, default: () => [] },
  aseguradoras: { type: Array, default: () => [] },
  roles: { type: Array, default: () => [] },
  filters: { type: Object, default: () => ({}) },
});

const showModal = ref(false);
const editingId = ref(null);
const search = ref(props.filters.search || '');

const form = useForm({
  tenant_id: '',
  nombre: '',
  cargo: '',
  email: '',
  telefono: '',
  rol: 'ejecutivo',
  activo: true,
});

const rolesLabels = {
  ejecutivo: 'Ejecutivo de Cuenta',
  director: 'Director Técnico',
  reinspector: 'Reinspector Senior',
  gerente: 'Gerencia Nacional',
  coordinador: 'Coordinador Siniestros',
};

function openCreate() {
  form.reset();
  editingId.value = null;
  showModal.value = true;
}

function openEdit(p) {
  editingId.value = p.id;
  form.tenant_id = p.tenant_id;
  form.nombre = p.nombre;
  form.cargo = p.cargo;
  form.email = p.email || '';
  form.telefono = p.telefono || '';
  form.rol = p.rol;
  form.activo = p.activo;
  showModal.value = true;
}

function submit() {
  if (editingId.value) {
    form.put(route('personal.update', editingId.value), {
      onSuccess: () => { showModal.value = false; },
    });
  } else {
    form.post(route('personal.store'), {
      onSuccess: () => { showModal.value = false; },
    });
  }
}

function destroy(id) {
  if (confirm('¿Está seguro de eliminar este registro?')) {
    router.delete(route('personal.destroy', id));
  }
}

function doSearch() {
  router.get(route('personal.index'), { search: search.value }, { preserveState: true });
}

// Stats
const totalPersonal = computed(() => props.personal.length);
</script>

<template>
  <Head :title="title" />

  <AppLayout :title="title">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Header Premium -->
      <div class="mb-10 flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div>
          <span class="text-xs font-bold uppercase tracking-widest text-primary-600 mb-2 block">Administración Interna</span>
          <h1 class="text-4xl font-extrabold text-slate-900 tracking-tight uppercase">Talento <span class="text-slate-400 font-light italic">Humano</span></h1>
          <p class="text-slate-500 mt-2 max-w-xl italic">Gestión de roles estratégicos, directores y ejecutivos autorizados para la operación nacional.</p>
        </div>

        <button @click="openCreate" class="group relative px-8 py-3 bg-slate-900 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest overflow-hidden transition-all hover:pr-12 shadow-xl shadow-slate-200">
            <span class="relative z-10">Vincular Personal</span>
            <svg class="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 opacity-0 group-hover:opacity-100 transition-all text-primary-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
        </button>
      </div>

      <!-- Filters & Search -->
      <div class="flex flex-col md:flex-row items-center gap-4 mb-8 bg-slate-50/50 p-4 rounded-3xl border border-slate-100 backdrop-blur-sm">
        <div class="relative flex-1 group">
          <input 
            v-model="search" 
            @keyup.enter="doSearch"
            type="text" 
            placeholder="Buscar por nombre, cargo o código operativo..."
            class="w-full pl-12 pr-4 py-3 bg-white border-transparent rounded-[1.25rem] text-sm font-medium focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-sm"
          />
          <svg class="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 transition-colors group-focus-within:text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>
        
        <button @click="doSearch" class="px-8 py-3 bg-slate-800 text-white rounded-[1.25rem] text-xs font-black uppercase tracking-widest hover:bg-slate-900 transition-all transform active:scale-95 shadow-lg shadow-slate-200">Sincronizar</button>
      </div>

      <!-- Table Container Premium -->
      <div class="bg-white rounded-[2.5rem] border border-slate-100 shadow-2xl overflow-hidden glass-morphism hidden md:block">
        <table class="w-full text-left border-collapse">
          <thead>
            <tr class="bg-slate-50/80 backdrop-blur-md">
              <th class="px-8 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 italic">Identidad / Operación</th>
              <th class="px-8 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 italic">Estructura / Rol</th>
              <th class="px-8 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 italic">Contacto</th>
              <th class="px-8 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 italic">Estatus</th>
              <th class="px-8 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 text-center italic">Comandos</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-50">
            <tr v-for="p in personal" :key="p.id" class="group hover:bg-primary-50/20 transition-all duration-300">
              <td class="px-8 py-6">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 rounded-[1.25rem] bg-gradient-to-br from-slate-100 to-slate-200 border border-white flex items-center justify-center text-slate-600 font-black text-sm uppercase group-hover:from-primary-500 group-hover:to-primary-600 group-hover:text-white group-hover:shadow-lg group-hover:shadow-primary-200 transition-all duration-500 group-hover:-rotate-3">
                        {{ p.nombre.substring(0, 2) }}
                    </div>
                    <div>
                        <p class="font-black text-slate-900 tracking-tight text-lg leading-none uppercase">{{ p.nombre }}</p>
                        <p class="text-[10px] text-slate-400 mt-2 font-mono font-black uppercase tracking-tighter">{{ p.codigo_sistema || 'ID-TBD' }}</p>
                    </div>
                </div>
              </td>
              <td class="px-8 py-6">
                <p class="text-[11px] font-black text-slate-500 uppercase tracking-wider mb-2 italic">{{ p.cargo }}</p>
                <span class="px-3 py-1 bg-white border border-slate-100 text-slate-600 text-[10px] font-black uppercase tracking-widest rounded-xl shadow-sm">
                  {{ rolesLabels[p.rol] || p.rol }}
                </span>
              </td>
              <td class="px-8 py-6">
                <div class="space-y-1">
                    <p class="text-xs font-black text-slate-800 tracking-tight lowercase transition-colors group-hover:text-primary-600">{{ p.email || '—' }}</p>
                    <p class="text-[10px] text-slate-400 font-bold tracking-widest">{{ p.telefono || '—' }}</p>
                </div>
              </td>
              <td class="px-8 py-6">
                <div class="flex items-center gap-2">
                    <span :class="p.activo ? 'bg-emerald-500' : 'bg-rose-500'" class="w-2 h-2 rounded-full animate-pulse"></span>
                    <span :class="p.activo ? 'text-emerald-700' : 'text-rose-700'" class="text-[10px] font-black uppercase tracking-[0.1em] italic">
                        {{ p.activo ? 'Vigente' : 'Inactivo' }}
                    </span>
                </div>
              </td>
              <td class="px-8 py-6 text-center">
                <div class="flex items-center justify-center gap-3 transform transition-all group-hover:translate-x-0 translate-x-4 opacity-0 group-hover:opacity-100">
                    <button @click="openEdit(p)" class="p-2.5 bg-white border border-slate-100 text-slate-600 rounded-2xl hover:bg-primary-600 hover:text-white hover:border-primary-600 transition-all duration-300 shadow-sm hover:shadow-lg">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                    </button>
                    <button @click="destroy(p.id)" class="p-2.5 bg-white border border-slate-100 text-rose-600 rounded-2xl hover:bg-rose-600 hover:text-white hover:border-rose-600 transition-all duration-300 shadow-sm hover:shadow-lg">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                    </button>
                </div>
              </td>
            </tr>
            <tr v-if="!personal.length">
                <td colspan="5" class="py-24 text-center">
                    <div class="w-24 h-24 bg-slate-50/50 rounded-full flex items-center justify-center mx-auto mb-6 border-2 border-dashed border-slate-200">
                        <svg class="w-12 h-12 text-slate-200" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                    </div>
                    <p class="text-xs font-black text-slate-400 uppercase tracking-widest italic">No se han registrado operativos en esta red.</p>
                </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Mobile Cards -->
      <div class="md:hidden space-y-3">
        <template v-if="personal.length > 0">
          <div v-for="p in personal" :key="p.id" class="bg-white rounded-2xl border border-slate-100 shadow-sm p-4 space-y-3">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center text-slate-600 font-bold text-sm uppercase flex-shrink-0">
                {{ p.nombre.substring(0, 2) }}
              </div>
              <div class="min-w-0 flex-1">
                <p class="font-bold text-slate-900 text-sm truncate uppercase">{{ p.nombre }}</p>
                <p class="text-[10px] text-slate-400 font-mono font-bold">{{ p.codigo_sistema || 'ID-TBD' }}</p>
              </div>
              <div class="flex items-center gap-1.5 flex-shrink-0">
                <span :class="p.activo ? 'bg-emerald-500' : 'bg-rose-500'" class="w-2 h-2 rounded-full"></span>
                <span :class="p.activo ? 'text-emerald-700' : 'text-rose-700'" class="text-[9px] font-bold uppercase">{{ p.activo ? 'Vigente' : 'Inactivo' }}</span>
              </div>
            </div>
            <div class="text-xs">
              <span class="text-[9px] text-slate-400 font-bold uppercase block">Cargo / Rol</span>
              <p class="text-slate-700 font-bold uppercase">{{ p.cargo }}</p>
              <span class="inline-block px-2 py-0.5 bg-white border border-slate-100 text-slate-600 text-[10px] font-bold uppercase rounded-lg mt-1">{{ rolesLabels[p.rol] || p.rol }}</span>
            </div>
            <div class="text-xs space-y-1">
              <span class="text-[9px] text-slate-400 font-bold uppercase block">Contacto</span>
              <p class="text-slate-700">{{ p.email || '—' }}</p>
              <p class="text-slate-400 text-[10px]">{{ p.telefono || '—' }}</p>
            </div>
            <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-50">
              <button @click="openEdit(p)" class="p-2 bg-white border border-slate-100 text-slate-600 rounded-xl hover:bg-primary-600 hover:text-white transition-all">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
              </button>
              <button @click="destroy(p.id)" class="p-2 bg-white border border-slate-100 text-rose-600 rounded-xl hover:bg-rose-600 hover:text-white transition-all">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
              </button>
            </div>
          </div>
        </template>
        <div v-else class="bg-white rounded-2xl border border-slate-100 shadow-sm p-8 text-center">
          <p class="text-slate-400 font-medium">No hay personal registrado.</p>
        </div>
      </div>

      <!-- Pagination Placeholder -->
      <div class="mt-8 flex justify-between items-center px-8">
        <p class="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] italic">Capacidad Operativa: {{ totalPersonal }} Perfiles vinculados</p>
      </div>
    </div>

    <!-- Modal Modal -->
    <div v-if="showModal" class="fixed inset-0 z-[100] overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen px-4 py-8">
            <div @click="showModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-md transition-opacity duration-300"></div>
            
            <div class="relative bg-white w-full max-w-2xl rounded-[3rem] shadow-2xl overflow-hidden glass-morphism border border-white/40">
                <div class="px-12 py-10 border-b border-slate-50 flex items-center justify-between bg-slate-50/50">
                    <div>
                        <h3 class="text-3xl font-black text-slate-900 tracking-tighter uppercase">{{ editingId ? 'Actualizar' : 'Vincular' }} Talento</h3>
                        <p class="text-[10px] text-slate-400 font-black uppercase tracking-[0.2em] mt-1 italic italic">Asignación de privilegios y jerarquía operativa</p>
                    </div>
                    <button @click="showModal = false" class="w-12 h-12 rounded-2xl bg-white shadow-xl flex items-center justify-center text-slate-400 hover:text-slate-900 transition-all hover:rotate-90">✕</button>
                </div>

                <form @submit.prevent="submit" class="p-12 space-y-8">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-10">
                        <div class="space-y-6">
                            <h4 class="text-[10px] font-black text-primary-600 uppercase tracking-[0.3em] flex items-center gap-2 italic">
                                <span class="w-4 h-px bg-primary-600"></span> Identidad / Dependencia
                            </h4>
                            
                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Entidad Asociada *</label>
                                <select v-model="form.tenant_id" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-xs font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all uppercase" required>
                                    <option value="" disabled>SELECCIONAR ENTIDAD...</option>
                                    <option v-for="a in aseguradoras" :key="a.id" :value="a.id">{{ a.nombre }}</option>
                                </select>
                            </div>

                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Nombre Completo *</label>
                                <input v-model="form.nombre" type="text" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-sm font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all uppercase" required />
                            </div>

                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Cargo en la Estructura *</label>
                                <input v-model="form.cargo" type="text" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-sm font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all uppercase" required />
                            </div>

                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Rol de Sistema *</label>
                                <select v-model="form.rol" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-xs font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all uppercase" required>
                                    <option v-for="r in roles" :key="r" :value="r">{{ rolesLabels[r] || r }}</option>
                                </select>
                            </div>
                        </div>

                        <div class="space-y-6">
                            <h4 class="text-[10px] font-black text-primary-600 uppercase tracking-[0.3em] flex items-center gap-2 italic">
                                <span class="w-4 h-px bg-primary-600"></span> Canales de Enlace
                            </h4>
                            
                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Email Corporativo</label>
                                <input v-model="form.email" type="email" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-sm font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all lowercase" />
                            </div>

                            <div>
                                <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block tracking-widest italic">Teléfono / Enlace Directo</label>
                                <input v-model="form.telefono" type="text" class="w-full px-6 py-4 bg-slate-50 border-transparent rounded-2xl text-sm font-bold focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all" />
                            </div>

                            <div v-if="editingId" class="pt-6">
                                <label class="flex items-center gap-3 cursor-pointer group">
                                    <div class="relative w-12 h-6 bg-slate-100 rounded-full transition-colors group-hover:bg-slate-200">
                                        <input v-model="form.activo" type="checkbox" class="absolute inset-0 opacity-0 cursor-pointer z-10" />
                                        <div :class="form.activo ? 'translate-x-6 bg-emerald-500' : 'translate-x-0 bg-slate-400'" class="w-6 h-6 rounded-full transition-all duration-300 shadow-md transform"></div>
                                    </div>
                                    <span class="text-xs font-black uppercase text-slate-600 tracking-widest italic">Acceso Habilitado</span>
                                </label>
                            </div>

                            <div class="p-6 bg-slate-50 rounded-3xl border border-slate-100 mt-6">
                                <p class="text-[10px] text-slate-400 font-bold leading-relaxed uppercase tracking-widest">
                                    <span class="text-primary-500 font-black italic">Nota:</span> Al registrar este talento, se habilitarán sus credenciales para la gestión operativa según su rol asignado.
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end gap-6 pt-10 border-t border-slate-50">
                        <button type="button" @click="showModal = false" class="px-8 py-4 text-xs font-black text-slate-400 uppercase tracking-[0.2em] hover:text-slate-900 transition-colors italic">Descartar Cambios</button>
                        <button type="submit" :disabled="form.processing" class="px-14 py-4 bg-slate-900 text-white rounded-[1.5rem] font-black uppercase text-[10px] tracking-[0.2em] hover:bg-primary-600 hover:shadow-2xl hover:shadow-primary-200 disabled:opacity-50 transition-all active:scale-95 transform">
                            {{ form.processing ? 'Sincronizando...' : (editingId ? 'Confirmar Ajustes' : 'Finalizar Registro') }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
  </AppLayout>
</template>

<style scoped>
.glass-morphism {
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
}
</style>

