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

const props = defineProps({
  title: { type: String, default: 'Brokers' },
  brokers: { 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: '',
  razon_social: '',
  telefono: '',
  email: '',
  contacto: '',
  activo: true,
});

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

function openEdit(b) {
  editingId.value = b.id;
  form.ruc = b.ruc;
  form.razon_social = b.razon_social;
  form.contacto = b.contacto || '';
  form.telefono = b.telefono || '';
  form.email = b.email || '';
  form.activo = b.activo;
  showModal.value = true;
}

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

function destroy(id) {
  if (confirm('¿Está seguro de eliminar este broker?')) {
    router.delete(route('brokers.destroy', id), { preserveScroll: true });
  }
}

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

// Stats
const totalBrokers = computed(() => props.brokers.total || props.brokers.data.length);
const activos = computed(() => props.brokers.data.filter(b => b.activo).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">Catálogos</span>
          <h1 class="text-4xl font-extrabold text-slate-900 tracking-tight">Brokers <span class="text-slate-400 font-light">de Seguros</span></h1>
          <p class="text-slate-500 mt-2 max-w-xl">Administración de intermediarios y compañías de corretaje.</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">Nuevo Broker</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>

      <div v-if="$page.props.flash?.message" class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-600 rounded-2xl p-4 flex items-center gap-3 shadow-sm">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
          <span class="text-sm font-bold">{{ $page.props.flash.message }}</span>
      </div>

      <div v-if="$page.props.flash?.error" class="mb-6 bg-rose-50 border border-rose-200 text-rose-600 rounded-2xl p-4 flex items-center gap-3 shadow-sm">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
          <span class="text-sm font-bold">{{ $page.props.flash.error }}</span>
      </div>

      <!-- Stats Cards Row -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-10">
        <div 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-blue-50 flex items-center justify-center text-blue-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                </div>
                <div>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Total Brokers</p>
                    <p class="text-xl font-bold text-slate-900">{{ totalBrokers }}</p>
                </div>
            </div>
        </div>
        <div 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-emerald-50 flex items-center justify-center text-emerald-600">
                    <svg class="w-6 h-6" 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>
                <div>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Brokers Activos</p>
                    <p class="text-xl font-bold text-slate-900">{{ activos }}</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 (Desktop) -->
      <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">Broker</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 uppercase">Teléfono</th>
              <th class="px-8 py-5 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 uppercase">Estado</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="b in brokers.data" :key="b.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">
                        {{ b.razon_social.substring(0, 1) }}
                    </div>
                    <div>
                        <p class="font-bold text-slate-900 leading-tight tracking-tight">{{ b.razon_social }}</p>
                    </div>
                </div>
              </td>
              <td class="px-8 py-6 text-sm font-mono text-slate-600">
                {{ b.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">{{ b.contacto || 'SIN CONTACTO' }}</p>
                    <p class="text-[10px] text-slate-400 font-medium">{{ b.email || '—' }}</p>
                </div>
              </td>
              <td class="px-8 py-6 text-sm text-slate-600">
                {{ b.telefono || '—' }}
              </td>
              <td class="px-8 py-6">
                <span :class="[
                    'px-3 py-1 rounded-lg text-xs font-bold font-mono',
                    b.activo ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'
                ]">
                    {{ b.activo ? 'Activo' : 'Inactivo' }}
                </span>
              </td>
              <td class="px-8 py-6 text-center whitespace-nowrap text-sm font-medium">
                  <button @click="openEdit(b)" class="text-indigo-600 hover:text-indigo-900 mr-3 font-semibold">Editar</button>
                  <button @click="destroy(b.id)" class="text-red-600 hover:text-red-900 font-semibold">Eliminar</button>
              </td>
            </tr>
            <tr v-if="!brokers.data.length">
                <td colspan="6" 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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                    </div>
                    <p class="text-slate-400 font-medium">No hay brokers registrados.</p>
                </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Mobile Cards -->
      <div class="md:hidden space-y-3">
        <template v-if="brokers.data.length > 0">
          <div v-for="b in brokers.data" :key="b.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 flex-shrink-0">
                {{ b.razon_social.substring(0, 1) }}
              </div>
              <div class="min-w-0 flex-1">
                <p class="font-bold text-slate-900 text-sm truncate">{{ b.razon_social }}</p>
              </div>
              <span :class="[
                  'px-2 py-0.5 rounded text-[10px] font-bold font-mono',
                  b.activo ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'
              ]">{{ b.activo ? 'Activo' : 'Inactivo' }}</span>
            </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-600">{{ b.ruc }}</span>
              </div>
              <div>
                <span class="text-[9px] text-slate-400 font-bold uppercase block">Teléfono</span>
                <span class="text-slate-600">{{ b.telefono || '—' }}</span>
              </div>
            </div>
            <div class="text-xs">
              <span class="text-[9px] text-slate-400 font-bold uppercase block">Contacto</span>
              <p class="font-bold text-slate-700">{{ b.contacto || 'SIN CONTACTO' }}</p>
              <p class="text-slate-400 text-[10px]">{{ b.email || '—' }}</p>
            </div>
            <div class="flex items-center justify-end gap-3 pt-2 border-t border-slate-50">
              <button @click="openEdit(b)" class="text-indigo-600 hover:text-indigo-900 font-bold text-xs uppercase tracking-widest">Editar</button>
              <button @click="destroy(b.id)" class="text-red-600 hover:text-red-900 font-bold text-xs uppercase tracking-widest">Eliminar</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 brokers registrados.</p>
        </div>
      </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' }} Broker</h3>
                        <p class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-1">Intermediario de Seguros</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 class="col-span-2">
                                <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 v-if="form.errors.ruc" class="text-xs text-rose-500 mt-1">{{ form.errors.ruc }}</div>
                            </div>
                            <div class="col-span-2">
                                <label class="form-label text-[10px] font-bold uppercase text-slate-400 mb-2 block">Razón Social *</label>
                                <input v-model="form.razon_social" 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 v-if="form.errors.razon_social" class="text-xs text-rose-500 mt-1">{{ form.errors.razon_social }}</div>
                            </div>
                        </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 Contacto</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">Nombre del Contacto</label>
                            <input v-model="form.contacto" 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 class="flex items-center gap-3">
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" v-model="form.activo" class="sr-only peer">
                                <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-500"></div>
                            </label>
                            <span class="text-sm font-bold text-slate-700">Broker Activo</span>
                        </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>
