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

const props = defineProps({
  title: String,
  casos: Object,
  estados: Object,
  aseguradoras: Array,
  filtros: Object
});

const page = usePage();
const searchQuery = ref(props.filtros?.search || '');
const selectedEstado = ref(props.filtros?.estado || '');
const showModal = ref(false);
const casoToDelete = ref(null);

const estadoColores = {
  pendiente_coordinacion: { bg: 'bg-slate-100', text: 'text-slate-700', label: 'Pendiente' },
  coordinado: { bg: 'bg-blue-100', text: 'text-blue-700', label: 'Coordinado' },
  mesa_compras: { bg: 'bg-amber-100', text: 'text-amber-700', label: 'Mesa Compras' },
  en_reparacion: { bg: 'bg-rose-100', text: 'text-rose-700', label: 'En Reparación' },
  analisis: { bg: 'bg-purple-100', text: 'text-purple-700', label: 'Análisis' },
  facturacion: { bg: 'bg-cyan-100', text: 'text-cyan-700', label: 'Facturación' },
  finalizado: { bg: 'bg-emerald-100', text: 'text-emerald-700', label: 'Finalizado' },
};

const filteredCasos = computed(() => {
  return props.casos.data || [];
});

const buscar = () => {
  const params = new URLSearchParams();
  if (searchQuery.value) params.set('search', searchQuery.value);
  if (selectedEstado.value) params.set('estado', selectedEstado.value);
  window.location.href = `/casos?${params.toString()}`;
};

const confirmDelete = (caso) => {
  casoToDelete.value = caso;
  showModal.value = true;
};

const deleteCaso = () => {
  if (casoToDelete.value) {
    const casoId = casoToDelete.value.id;
    casoToDelete.value = null;
    showModal.value = false;
    window.location.href = `/casos/${casoId}`;
  }
};

const cancelDelete = () => {
  casoToDelete.value = null;
  showModal.value = false;
};
</script>

<template>
  <AppLayout :title="title">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
        <div>
          <h2 class="text-2xl font-bold text-slate-800">Casos</h2>
          <p class="text-slate-500">Gestión de casos de siniestros</p>
        </div>
        <Link 
          href="/casos/create" 
          class="inline-flex items-center gap-2 px-5 py-3 bg-brand-blue text-white rounded-xl font-semibold hover:bg-brand-blue/90 transition-all shadow-lg hover:shadow-xl"
        >
          <font-awesome-icon :icon="['fas', 'plus']" class="w-5 h-5" />
          Nuevo Caso
        </Link>
      </div>

      <!-- Filters -->
      <div class="flex flex-col md:flex-row gap-4 bg-white p-4 rounded-xl shadow-sm border border-slate-200">
        <div class="flex-1 relative">
          <font-awesome-icon :icon="['fas', 'search']" class="w-5 h-5 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" />
          <input 
            v-model="searchQuery"
            type="text" 
            placeholder="Buscar por placa, cliente o número..."
            class="w-full pl-12 pr-4 py-2.5 rounded-lg border-2 border-slate-200 focus:border-brand-blue focus:ring-0"
            @keyup.enter="buscar"
          >
        </div>
        <select 
          v-model="selectedEstado"
          class="px-4 py-2.5 rounded-lg border-2 border-slate-200 bg-white focus:border-brand-blue focus:ring-0"
          @change="buscar"
        >
          <option value="">Todos los estados</option>
          <option v-for="(label, key) in estados" :key="key" :value="key">{{ label }}</option>
        </select>
        <select 
          v-if="aseguradoras.length"
          class="px-4 py-2.5 rounded-lg border-2 border-slate-200 bg-white focus:border-brand-blue focus:ring-0"
          @change="buscar"
        >
          <option value="">Todas las aseguradoras</option>
          <option v-for="a in aseguradoras" :key="a.id" :value="a.id">{{ a.nombre }}</option>
        </select>
      </div>

      <!-- Table -->
      <div class="bg-white rounded-2xl shadow-lg border border-slate-200 overflow-hidden">
        <div class="overflow-x-auto hide-scrollbar">
          <table class="w-full block md:table">
            <thead class="hidden md:table-header-group bg-gradient-to-r from-slate-50 to-slate-100">
              <tr>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Número</th>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Fecha</th>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Placa</th>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Cliente</th>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Aseguradora</th>
                <th class="px-6 py-4 text-left text-sm font-bold text-slate-700">Estado</th>
                <th class="px-6 py-4 text-right text-sm font-bold text-slate-700">Acciones</th>
              </tr>
            </thead>
            <tbody class="block md:table-row-group divide-y md:divide-slate-100 space-y-4 md:space-y-0 p-4 md:p-0 bg-slate-50/50 md:bg-white">
              <tr 
                v-for="caso in filteredCasos" 
                :key="caso.id"
                class="block md:table-row bg-white rounded-2xl md:rounded-none shadow-sm md:shadow-none border border-slate-100 md:border-0 hover:bg-slate-50/50 transition-colors group"
              >
                <!-- Mobile Card View -->
                <td class="block md:hidden p-5">
                  <div class="flex justify-between items-start mb-4">
                    <div>
                      <span class="block font-black text-slate-800 text-lg tracking-tight">{{ caso.numero_reclamo }}</span>
                      <span class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">{{ caso.fecha_siniestro ? caso.fecha_siniestro.split('T')[0] : 'N/A' }}</span>
                    </div>
                    <span 
                      :class="[
                        'inline-block px-3 py-1.5 rounded-lg text-[10px] font-bold tracking-widest uppercase shadow-sm',
                        estadoColores[caso.estado_actual]?.bg || 'bg-slate-100',
                        estadoColores[caso.estado_actual]?.text || 'text-slate-700'
                      ]"
                    >
                      {{ estados[caso.estado_actual] || caso.estado_actual }}
                    </span>
                  </div>
                  
                  <div class="flex items-center gap-3 bg-slate-50 p-3 rounded-xl border border-slate-100 mb-4">
                    <div class="bg-slate-800 text-white text-[10px] px-2.5 py-1.5 rounded-lg font-bold leading-tight shadow-sm whitespace-nowrap">
                      {{ caso.vehiculo?.placa || 'N/A' }}
                    </div>
                    <div class="flex flex-col">
                      <span class="text-xs font-bold text-slate-700 truncate max-w-[150px]">{{ caso.cliente?.nombre || 'N/A' }}</span>
                      <span class="text-[10px] font-semibold text-slate-500 truncate max-w-[150px]">{{ caso.aseguradora?.nombre || 'N/A' }}</span>
                    </div>
                  </div>

                  <div class="flex justify-end gap-2 border-t border-slate-100 pt-4">
                    <Link 
                      :href="`/casos/${caso.id}`" 
                      class="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl bg-blue-50 text-blue-600 font-bold text-[10px] uppercase tracking-widest hover:bg-blue-100 transition-colors"
                    >
                      <font-awesome-icon :icon="['fas', 'eye']" class="w-3.5 h-3.5" />
                      Detalles
                    </Link>
                    <button 
                      @click="confirmDelete(caso)"
                      class="px-4 py-2.5 rounded-xl bg-red-50 text-red-500 hover:bg-red-100 transition-colors"
                    >
                      <font-awesome-icon :icon="['fas', 'trash']" class="w-3.5 h-3.5" />
                    </button>
                  </div>
                </td>

                <!-- Desktop Table View -->
                <td class="hidden md:table-cell px-6 py-4 whitespace-nowrap">
                  <span class="inline-block font-bold text-slate-800">{{ caso.numero_reclamo }}</span>
                </td>
                <td class="hidden md:table-cell px-6 py-4 text-slate-600 text-sm whitespace-nowrap">
                  {{ caso.fecha_siniestro ? caso.fecha_siniestro.split('T')[0] : 'N/A' }}
                </td>
                <td class="hidden md:table-cell px-6 py-4 whitespace-nowrap">
                  <span class="inline-block px-3 py-1 rounded-lg bg-slate-800 text-white font-medium text-sm whitespace-nowrap">
                    {{ caso.vehiculo?.placa || 'N/A' }}
                  </span>
                </td>
                <td class="hidden md:table-cell px-6 py-4 text-slate-600 max-w-xs truncate">{{ caso.cliente?.nombre || 'N/A' }}</td>
                <td class="hidden md:table-cell px-6 py-4 text-slate-600">{{ caso.aseguradora?.nombre || 'N/A' }}</td>
                <td class="hidden md:table-cell px-6 py-4 whitespace-nowrap">
                  <span 
                    :class="[
                      'inline-block px-3 py-1 rounded-full text-xs font-semibold whitespace-nowrap',
                      estadoColores[caso.estado_actual]?.bg || 'bg-slate-100',
                      estadoColores[caso.estado_actual]?.text || 'text-slate-700'
                    ]"
                  >
                    {{ estados[caso.estado_actual] || caso.estado_actual }}
                  </span>
                </td>
                <td class="hidden md:table-cell px-6 py-4 text-right">
                  <div class="flex items-center justify-end gap-2">
                    <Link 
                      :href="`/casos/${caso.id}`" 
                      class="p-2 rounded-lg hover:bg-brand-blue/10 text-brand-blue transition-colors"
                      title="Ver caso"
                    >
                      <font-awesome-icon :icon="['fas', 'eye']" class="w-5 h-5" />
                    </Link>
                    <button 
                      @click="confirmDelete(caso)"
                      class="p-2 rounded-lg hover:bg-red-50 text-red-500 transition-colors opacity-0 group-hover:opacity-100"
                      title="Eliminar caso"
                    >
                      <font-awesome-icon :icon="['fas', 'trash']" class="w-5 h-5" />
                    </button>
                  </div>
                </td>
              </tr>
              <tr v-if="filteredCasos.length === 0">
                <td colspan="7" class="block md:table-cell px-6 py-12 text-center bg-white rounded-2xl md:rounded-none">
                  <div class="w-20 h-20 mx-auto mb-4 rounded-full bg-slate-100 flex items-center justify-center">
                    <font-awesome-icon :icon="['fas', 'folder-open']" class="w-10 h-10 text-slate-400" />
                  </div>
                  <p class="text-slate-500 text-lg mb-2">No hay casos registrados</p>
                  <Link href="/casos/create" class="inline-flex items-center gap-2 px-4 py-2 bg-brand-blue text-white rounded-lg hover:bg-brand-blue/90 transition-colors">
                    <font-awesome-icon :icon="['fas', 'plus']" class="w-4 h-4" />
                    Crear primer caso
                  </Link>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div v-if="casos.links" class="px-6 py-4 border-t border-slate-100 flex justify-between items-center bg-slate-50">
          <p class="text-sm text-slate-500">
            Mostrando {{ casos.from || 0 }} - {{ casos.to || 0 }} de {{ casos.total }} resultados
          </p>
          <div class="flex gap-1">
            <template v-for="link in casos.links" :key="link.label">
              <Link 
                v-if="link.url"
                :href="link.url"
                :class="[
                  'px-3 py-1.5 rounded text-sm font-medium',
                  link.active ? 'bg-brand-blue text-white shadow' : 'bg-white text-slate-600 hover:bg-slate-100 border border-slate-200'
                ]"
                v-html="link.label"
              />
              <span 
                v-else
                class="px-3 py-1.5 rounded text-sm bg-slate-100 text-slate-400 cursor-not-allowed"
                v-html="link.label"
              />
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- Delete Modal -->
    <div v-if="showModal" class="fixed inset-0 z-50 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-slate-900 bg-opacity-75 transition-opacity" aria-hidden="true" @click="cancelDelete"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                <svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 class="text-lg leading-6 font-bold text-slate-900" id="modal-title">
                  Eliminar Caso
                </h3>
                <div class="mt-2">
                  <p class="text-sm text-slate-500">
                    ¿Está seguro de que desea eliminar el caso <strong class="text-slate-800">{{ casoToDelete?.numero_reclamo }}</strong>?
                  </p>
                  <p class="text-sm text-red-500 mt-2">
                    Esta acción eliminará también:
                  </p>
                  <ul class="text-xs text-slate-500 mt-1 list-disc list-inside">
                    <li>Datos del cliente</li>
                    <li>Datos del vehículo</li>
                    <li>Historial de estados</li>
                    <li>Notificaciones</li>
                    <li>Cotizaciones y facturas</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-slate-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <form :action="`/casos/${casoToDelete?.id}`" method="POST">
              <input type="hidden" name="_method" value="DELETE">
              <input type="hidden" name="_token" :value="$page.props.csrf_token">
              <button 
                type="submit"
                class="w-full inline-flex justify-center rounded-xl border border-transparent px-4 py-2 text-base font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm"
              >
                Eliminar Caso
              </button>
            </form>
            <button 
              @click="cancelDelete"
              class="mt-3 w-full inline-flex justify-center rounded-xl border border-slate-300 px-4 py-2 bg-white text-base font-medium text-slate-700 hover:bg-slate-50 focus:outline-none sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
            >
              Cancelar
            </button>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>
