<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,
  aseguradoras: { type: Object, default: () => ({ data: [] }) },
  filtros: { type: Object, default: () => ({}) },
});

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

const form = useForm({
  ruc: '',
  nombre: '',
  id_externo: '',
  telefono: '',
  email: '',
  direccion: '',
  ciudad: '',
  tipo: 'empresa',
  corte_facturacion_dia: 30,
  cruce_facturacion_dia: 5,
});

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

function openEdit(a) {
  editingId.value = a.id;
  form.ruc = a.ruc;
  form.nombre = a.nombre;
  form.id_externo = a.id_externo || '';
  form.telefono = a.telefono || '';
  form.email = a.email || '';
  form.direccion = a.direccion || '';
  form.ciudad = a.ciudad || '';
  form.tipo = a.tipo || 'empresa';
  form.corte_facturacion_dia = a.corte_facturacion_dia || 30;
  form.cruce_facturacion_dia = a.cruce_facturacion_dia || 5;
  showModal.value = true;
}

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

function destroy(id) {
  if (confirm('¿Está seguro de eliminar esta aseguradora?')) {
    router.delete(route('aseguradoras.destroy', id));
  }
}

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

// Stats
const totalAseguradoras = computed(() => props.aseguradoras.data.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">Socios Estratégicos</span>
          <h1 class="text-4xl font-extrabold text-slate-900 tracking-tight">Compañías <span class="text-slate-400 font-light">de Seguros</span></h1>
          <p class="text-slate-500 mt-2 max-w-xl">Administración de aseguradoras, configuración de identificadores externos para integración con SIAS/Audatex.</p>
        </div>

        <button @click="openCreate" class="group relative px-8 py-3 bg-slate-900 text-white rounded-2xl font-bold overflow-hidden transition-all hover:pr-12 shadow-xl shadow-slate-200">
            <span class="relative z-10">Nueva Aseguradora</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" 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>

      <!-- Stats Cards Row (Simplified) -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
        <div v-for="(stat, idx) in [
            { label: 'Aseguradoras Activas', val: totalAseguradoras, icon: 'ShieldCheck', color: 'blue' },
            { label: 'Casos Totales (Mes)', val: '1,240', icon: 'FileText', color: 'emerald' },
            { label: 'Integraciones SIAS', val: totalAseguradoras, icon: 'RefreshCw', color: 'indigo' }
        ]" :key="idx" class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm">
            <div class="flex items-center gap-4">
                <div :class="`w-12 h-12 rounded-2xl bg-${stat.color}-50 flex items-center justify-center text-${stat.color}-600`">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path v-if="stat.icon === 'ShieldCheck'" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                        <path v-if="stat.icon === 'FileText'" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        <path v-if="stat.icon === 'RefreshCw'" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                </div>
                <div>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{{ stat.label }}</p>
                    <p class="text-xl font-bold text-slate-900">{{ stat.val }}</p>
                </div>
            </div>
        </div>
      </div>

      <!-- Filters & Search -->
      <div class="flex flex-col md:flex-row items-center gap-4 mb-8 bg-slate-50/50 p-4 rounded-2xl border border-slate-100">
        <div class="relative flex-1 group">
          <input 
            v-model="search" 
            @keyup.enter="doSearch"
            type="text" 
            placeholder="Buscar por RUC o Razón Social..."
            class="w-full pl-12 pr-4 py-3 bg-white border-transparent rounded-xl text-sm 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-400" 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-6 py-3 bg-slate-800 text-white rounded-xl text-sm font-bold hover:bg-slate-900 transition-colors">Filtrar lista</button>
      </div>

      <!-- Main Content Container -->
      <div class="bg-white rounded-[2.5rem] border border-slate-100 shadow-xl overflow-hidden glass-morphism hidden md:block">
        <table class="w-full text-left border-collapse">
          <thead>
            <tr class="bg-slate-50/50">
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 uppercase">Aseguradora</th>
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 uppercase">ID Externo</th>
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 uppercase">RUC</th>
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 uppercase">Contacto</th>
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 text-center uppercase">Acciones</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-50">
            <tr v-for="a in aseguradoras.data" :key="a.id" class="group hover:bg-primary-50/30 transition-colors">
              <td class="px-8 py-6">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center text-slate-500 font-bold group-hover:bg-primary-600 group-hover:text-white transition-colors">
                        {{ a.nombre.substring(0, 1) }}
                    </div>
                    <div>
                        <p class="font-bold text-slate-900 leading-tight uppercase tracking-tight">{{ a.nombre }}</p>
                        <p class="text-xs text-slate-400 mt-1 uppercase font-bold">{{ a.tipo }}</p>
                    </div>
                </div>
              </td>
              <td class="px-8 py-6">
                <span class="px-3 py-1 bg-slate-100 text-slate-600 rounded-lg text-xs font-bold font-mono">{{ a.id_externo || 'S/N' }}</span>
              </td>
              <td class="px-8 py-6 text-sm font-mono text-slate-600">
                {{ a.ruc }}
              </td>
              <td class="px-8 py-6">
                <div class="flex flex-col gap-1">
                    <p class="text-xs font-bold text-slate-700 tracking-wider transition-colors group-hover:text-primary-600">{{ a.email || 'SIN EMAIL' }}</p>
                    <p class="text-[10px] text-slate-400 font-medium">{{ a.telefono || '—' }}</p>
                </div>
              </td>
              <td class="px-8 py-6 text-center">
                <div class="flex items-center justify-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button @click="openEdit(a)" class="p-2 bg-slate-50 text-slate-600 rounded-lg hover:bg-primary-600 hover:text-white">
                        <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                    </button>
                    <button @click="destroy(a.id)" class="p-2 bg-slate-50 text-red-600 rounded-lg hover:bg-red-600 hover:text-white">
                        <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="!aseguradoras.data.length">
                <td colspan="5" class="px-8 py-20 text-center">
                    <div class="w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-10 h-10 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" /></svg>
                    </div>
                    <p class="text-slate-400 font-medium">No hay aseguradoras registradas.</p>
                </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Mobile Cards -->
      <div class="md:hidden space-y-3">
        <template v-if="aseguradoras.data.length > 0">
          <div v-for="a in aseguradoras.data" :key="a.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-slate-100 flex items-center justify-center text-slate-500 font-bold text-sm flex-shrink-0">
                {{ a.nombre.substring(0, 1) }}
              </div>
              <div class="min-w-0 flex-1">
                <p class="font-bold text-slate-900 text-sm truncate uppercase">{{ a.nombre }}</p>
                <p class="text-[10px] text-slate-400 font-bold uppercase">{{ a.tipo }}</p>
              </div>
            </div>
            <div class="grid grid-cols-2 gap-2 text-xs">
              <div>
                <span class="text-[9px] text-slate-400 font-bold uppercase block">RUC</span>
                <span class="font-mono text-slate-700">{{ a.ruc }}</span>
              </div>
              <div>
                <span class="text-[9px] text-slate-400 font-bold uppercase block">ID Externo</span>
                <span class="px-2 py-0.5 bg-slate-100 text-slate-600 rounded text-[10px] font-bold font-mono">{{ a.id_externo || 'S/N' }}</span>
              </div>
            </div>
            <div class="text-xs">
              <span class="text-[9px] text-slate-400 font-bold uppercase block">Contacto</span>
              <p class="text-slate-700">{{ a.email || 'SIN EMAIL' }}</p>
              <p class="text-slate-400 text-[10px]">{{ a.telefono || '—' }}</p>
            </div>
            <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-50">
              <button @click="openEdit(a)" class="p-2 bg-slate-50 text-slate-600 rounded-lg 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
              </button>
              <button @click="destroy(a.id)" class="p-2 bg-slate-50 text-red-600 rounded-lg hover:bg-red-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 aseguradoras registradas.</p>
        </div>
      </div>

      <!-- Pagination Placeholder -->
      <div class="mt-8 flex justify-between items-center px-4">
        <p class="text-xs font-bold text-slate-400 uppercase tracking-widest">Aseguradoras registradas: {{ totalAseguradoras }}</p>
      </div>
    </div>

    <!-- Modal Premium -->
    <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/40 backdrop-blur-sm transition-opacity"></div>
            
            <div class="relative bg-white w-full max-w-xl rounded-[2.5rem] shadow-2xl overflow-hidden border border-white/20">
                <div class="px-10 py-8 border-b border-slate-50 flex items-center justify-between bg-slate-50/30">
                    <div>
                        <h3 class="text-2xl font-black text-slate-900 tracking-tight uppercase">{{ editingId ? 'Actualizar' : 'Registrar' }} Aseguradora</h3>
                        <p class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-1">Sincronización de catálogos SIAS</p>
                    </div>
                    <button @click="showModal = false" class="w-10 h-10 rounded-full bg-white shadow-sm flex items-center justify-center text-slate-400 hover:text-slate-900 transition-colors">✕</button>
                </div>

                <form @submit.prevent="submit" class="p-10 space-y-6">
                    <div class="space-y-6">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">RUC *</label>
                                <input v-model="form.ruc" type="text" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" required />
                            </div>
                            <div>
                                <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">ID Externo (SIAS/Audatex) *</label>
                                <input v-model="form.id_externo" type="text" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" required />
                            </div>
                        </div>

                        <div>
                            <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Razón Social *</label>
                            <input v-model="form.nombre" type="text" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" required />
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Email de Notificación</label>
                                <input v-model="form.email" type="email" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" />
                            </div>
                            <div>
                                <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Teléfono Principal</label>
                                <input v-model="form.telefono" type="text" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" />
                            </div>
                        </div>

                        <div>
                            <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Ciudad</label>
                            <input v-model="form.ciudad" type="text" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner" />
                        </div>

                        <div>
                            <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Dirección Matriz</label>
                            <textarea v-model="form.direccion" rows="3" class="w-full px-5 py-3 bg-slate-50 border-transparent rounded-2xl text-sm focus:ring-2 focus:ring-primary-500 focus:bg-white transition-all shadow-inner"></textarea>
                        </div>

                        <!-- Parámetros de Facturación (Módulo 5) -->
                        <div class="p-6 bg-slate-50 rounded-3xl border border-slate-100">
                            <h4 class="text-[10px] font-bold uppercase text-slate-400 mb-4 tracking-widest flex items-center gap-2">
                                <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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                                Parámetros de Facturación
                            </h4>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="text-[10px] font-bold text-slate-500 mb-1 block">Día de Corte</label>
                                    <input v-model="form.corte_facturacion_dia" type="number" min="1" max="31" class="w-full px-4 py-2 bg-white border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-primary-500" />
                                </div>
                                <div>
                                    <label class="text-[10px] font-bold text-slate-500 mb-1 block">Día de Cruce</label>
                                    <input v-model="form.cruce_facturacion_dia" type="number" min="1" max="31" class="w-full px-4 py-2 bg-white border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-primary-500" />
                                </div>
                            </div>
                            <p class="text-[9px] text-slate-400 mt-3 italic">* Se usará para automatizar estados de pago y alertas de conciliación.</p>
                        </div>
                    </div>

                    <div class="flex justify-end gap-4 pt-8 border-t border-slate-50">
                        <button type="button" @click="showModal = false" class="px-8 py-3 text-sm font-bold text-slate-400 uppercase tracking-widest hover:text-slate-900 transition-colors">Cancelar</button>
                        <button type="submit" :disabled="form.processing" class="px-10 py-3 bg-slate-900 text-white rounded-2xl font-bold uppercase text-[10px] tracking-widest hover:bg-slate-800 disabled:opacity-50 shadow-xl shadow-slate-200 transition-all active:scale-95">
                            {{ form.processing ? 'Procesando...' : (editingId ? 'Actualizar' : 'Registrar') }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
  </AppLayout>
</template>

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

