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

const props = defineProps({
  title: String,
  caso: Object,
  estados: Object
});

const form = useForm({
  estado_actual: props.caso.estado_actual || 'pendiente_coordinacion',
  nota: '',
  sub_estado_taller: ''
});

const search = ref('');
const filteredEstados = computed(() => {
    if (!search.value) return props.estados;
    const result = {};
    Object.keys(props.estados).forEach(key => {
        if (props.estados[key].toLowerCase().includes(search.value.toLowerCase())) {
            result[key] = props.estados[key];
        }
    });
    return result;
});

const submitting = ref(false);

const submit = () => {
    submitting.value = true;
    form.post(route('casos.update_estado', props.caso.id), {
        onSuccess: () => {
            form.nota = '';
            form.sub_estado_taller = '';
        },
        onFinish: () => submitting.value = false
    });
};

const estadoColores = {
  // Inicial
  pendiente_coordinacion: 'bg-slate-50 text-slate-700 border-slate-200',
  recoordinacion: 'bg-slate-100 text-slate-800 border-slate-300',
  
  // En progreso / Logística
  coordinado: 'bg-blue-50 text-blue-700 border-blue-200',
  caso_en_ruta: 'bg-indigo-50 text-indigo-700 border-indigo-200',
  
  // Proformas / Espera
  pendiente_proforma_cliente: 'bg-amber-50 text-amber-700 border-amber-200',
  pendiente_proforma_taller: 'bg-amber-50 text-amber-700 border-amber-200',
  no_contesta: 'bg-orange-50 text-orange-700 border-orange-200',
  llamar_despues: 'bg-orange-50 text-orange-600 border-orange-200',
  vehiculo_retenido: 'bg-red-50 text-red-700 border-red-200',
  
  // Análisis e Inspección
  analisis: 'bg-fuchsia-50 text-fuchsia-700 border-fuchsia-200',
  inspeccion_realizada: 'bg-purple-50 text-purple-700 border-purple-200',
  elaboracion_informe: 'bg-violet-50 text-violet-700 border-violet-200',
  
  // Autorizaciones
  confirmacion_cobertura: 'bg-cyan-50 text-cyan-700 border-cyan-200',
  autorizacion_inspector: 'bg-sky-50 text-sky-700 border-sky-200',
  autorizacion_reinspector: 'bg-sky-50 text-sky-700 border-sky-200',
  autorizacion_ejecutivo: 'bg-sky-50 text-sky-700 border-sky-200',
  
  // Operaciones
  mesa_compras: 'bg-yellow-50 text-yellow-700 border-yellow-200',
  en_reparacion: 'bg-rose-50 text-rose-700 border-rose-200',
  
  // Final
  facturacion: 'bg-teal-50 text-teal-700 border-teal-200',
  finalizado: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  rechazado: 'bg-stone-100 text-stone-700 border-stone-300',
};

</script>

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

  <AppLayout :title="title">
    <div class="max-w-6xl mx-auto space-y-8 animate-fade-in-up">
      
      <!-- Premium Header -->
      <div class="relative overflow-hidden bg-white/70 backdrop-blur-2xl rounded-3xl p-8 border border-white/80 shadow-[0_8px_30px_rgb(0,0,0,0.04)] ring-1 ring-slate-100/50">
        <div class="absolute top-0 right-0 -mt-16 -mr-16 w-64 h-64 bg-gradient-to-br from-blue-400/10 to-indigo-500/10 rounded-full blur-3xl pointer-events-none"></div>
        <div class="absolute bottom-0 left-0 w-32 h-32 bg-gradient-to-tr from-rose-400/10 to-amber-400/10 rounded-full blur-2xl pointer-events-none"></div>

        <div class="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div class="flex flex-col gap-3">
            <Link :href="route('coordinacion')" class="flex items-center gap-2 text-sm font-semibold text-slate-500 hover:text-blue-600 transition-colors w-max group">
              <span class="bg-white rounded-full p-1.5 shadow-sm border border-slate-100 group-hover:scale-110 group-hover:shadow-md 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="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
              </span>
              Volver a Coordinación
            </Link>
            
            <h1 class="text-3xl lg:text-4xl font-black text-slate-900 tracking-tight mt-2">Gestión de Estados</h1>
            <div class="flex items-center gap-4 mt-1">
              <span class="text-slate-500 font-medium">Siniestro: <strong class="text-slate-800">{{ caso.numero_reclamo }}</strong></span>
              <span class="w-1.5 h-1.5 rounded-full bg-slate-300"></span>
              <span class="text-slate-500 font-medium">Placa: <strong class="text-slate-800 border-b-2 border-slate-800/20 pb-0.5">{{ caso.vehiculo?.placa }}</strong></span>
            </div>
          </div>

          <div class="flex gap-2">
             <Link :href="route('timeline')" class="flex items-center gap-2 px-5 py-2.5 bg-white text-slate-700 font-bold rounded-xl shadow-sm border border-slate-200 hover:bg-slate-50 hover:shadow-md transition-all active:scale-95">
              <svg class="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
              Ver Timeline Completo
             </Link>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Panel de Cambio de Estado -->
        <div class="lg:col-span-1 space-y-6">
          <div class="bg-white rounded-3xl p-8 shadow-[0_4px_20px_rgb(0,0,0,0.03)] border border-slate-100 relative overflow-hidden group">
            <div class="absolute top-0 right-0 w-32 h-32 bg-slate-50 rounded-full -mt-10 -mr-10 transition-transform group-hover:scale-110 duration-500 pointer-events-none"></div>
            
            <div class="flex items-center gap-3 mb-6 relative z-10">
               <div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center text-blue-600 shadow-sm border border-blue-200/50">
                  <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="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"></path></svg>
               </div>
               <h3 class="text-xl font-bold text-slate-800">Actualizar Estado</h3>
            </div>
            
            <form @submit.prevent="submit" class="space-y-6 relative z-10">
              <div class="space-y-1.5">
                <label class="text-xs font-bold text-slate-500 uppercase tracking-widest">Nuevo Estado *</label>
                <div class="relative">
                   <select v-model="form.estado_actual" class="w-full bg-slate-50/50 border border-slate-200 text-slate-800 font-bold rounded-xl px-4 py-3 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-shadow shadow-sm" required>
                      <option v-for="(label, key) in estados" :key="key" :value="key">
                        {{ label }}
                      </option>
                   </select>
                </div>
              </div>

              <div v-if="['pendiente_coordinacion', 'recoordinacion', 'en_reparacion', 'taller'].includes(form.estado_actual)" class="space-y-1.5 animate-fade-in-up" style="animation-duration: 0.3s;">
                <label class="text-xs font-bold text-slate-500 uppercase tracking-widest">Sub-estado Taller <span class="text-slate-400 font-normal">(Opcional)</span></label>
                <select v-model="form.sub_estado_taller" class="w-full bg-slate-50/50 border border-slate-200 text-slate-700 font-medium rounded-xl px-4 py-3 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-shadow shadow-sm">
                  <option value="">Ninguno</option>
                  <option value="dealer_repuestos_completos">Dealer – repuestos completos</option>
                  <option value="multimarca">Multimarca</option>
                  <option value="dealer_multimarca">Dealer Multimarca</option>
                  <option value="taller_aseguradora">Taller asegurado</option>
                </select>
              </div>

              <div class="space-y-1.5">
                <label class="text-xs font-bold text-slate-500 uppercase tracking-widest flex justify-between">
                  <span>Nota / Observación *</span>
                  <span class="text-slate-400 font-normal normal-case">Máx 200 pal.</span>
                </label>
                <textarea 
                  v-model="form.nota" 
                  rows="5" 
                  class="w-full border text-slate-700 font-medium rounded-xl px-4 py-3 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-shadow shadow-sm resize-none" 
                  :class="{'border-amber-300 bg-amber-50/50': !form.nota, 'bg-slate-50/50 border-slate-200': form.nota}"
                  placeholder="Describa los motivos o detalles del cambio..."
                  required
                ></textarea>
                
                <div class="flex items-start gap-2 mt-2">
                   <div v-if="!form.nota" class="text-amber-500 mt-0.5 animate-pulse">
                      <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path></svg>
                   </div>
                   <div v-else class="text-emerald-500 mt-0.5">
                      <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>
                   </div>
                   <p v-if="!form.nota" class="text-xs text-amber-600 font-semibold">Se requiere una nota descriptiva para habilitar el guardado.</p>
                   <p v-else class="text-xs text-slate-500 font-medium">Nota lista para ser guardada en el historial.</p>
                </div>
              </div>

              <div class="pt-2">
                <button 
                  type="submit" 
                  :disabled="submitting || !form.nota" 
                  class="w-full flex items-center justify-center gap-2 py-3.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-500 transition-all shadow-lg shadow-blue-600/30 hover:shadow-blue-600/50 disabled:opacity-50 disabled:hover:bg-blue-600 disabled:hover:shadow-blue-600/30 disabled:scale-100 hover:-translate-y-0.5 active:scale-95"
                >
                  <svg v-if="submitting" class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                  <svg v-else 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>{{ submitting ? 'Guardando en blockchain...' : 'Confirmar Nuevo Estado' }}</span>
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- Línea de Tiempo del Historial -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-[2rem] p-8 lg:min-h-full">
            <div class="flex items-center gap-4 mb-10">
               <div class="w-12 h-12 rounded-2xl bg-purple-50 flex items-center justify-center text-purple-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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
               </div>
               <h3 class="text-2xl font-bold text-slate-800 tracking-tight">Recorrido del Siniestro</h3>
            </div>
            
            <div class="relative pl-2 mt-4">
              <!-- Timeline Line -->
              <div class="absolute left-6 top-8 bottom-8 w-0.5 bg-blue-200/60 rounded-full"></div>
              
              <div class="space-y-8 relative">
                <div v-for="(log, index) in caso.estados_historicos" :key="log.id" class="relative pl-14">
                   
                   <!-- Timeline Node -->
                   <div v-if="index === 0" class="absolute left-[19px] top-8 w-2.5 h-2.5 rounded-full bg-blue-500 ring-4 ring-blue-50"></div>
                   <div v-else class="absolute left-[19px] top-8 w-2.5 h-2.5 rounded-full bg-slate-300 ring-4 ring-slate-50"></div>
                   
                   <!-- Card Content exactly matching the SAAS design in screenshot -->
                   <div class="bg-white border border-slate-900 rounded-[1.5rem] p-6 shadow-sm">
                      
                      <div class="flex justify-between items-start mb-4">
                         <!-- Status Left -->
                         <div class="bg-slate-50 px-3 py-1.5 rounded-xl flex items-center gap-3">
                           <span class="text-[10px] font-bold uppercase tracking-widest text-slate-600">
                             {{ estados[log.estado] || log.estado }}
                           </span>
                           <span v-if="index === 0" class="w-3 h-3 rounded-full bg-emerald-400 border border-emerald-500/20"></span>
                         </div>
                         
                         <!-- Date Right -->
                         <div class="bg-slate-50 px-3 py-1.5 rounded-xl text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                            {{ new Date(log.created_at).toLocaleString('es-ES', { day: '2-digit', month: 'short', hour: '2-digit', minute:'2-digit' }).replace('.', '').replace(',', '') }}
                         </div>
                      </div>

                      <div v-if="log.sub_estado_taller" class="mb-4">
                         <span class="px-2.5 py-1 rounded-lg text-[9px] font-bold uppercase tracking-widest bg-purple-50 text-purple-600">
                           {{ log.sub_estado_taller.replace(/_/g, ' ') }}
                         </span>
                      </div>
                      
                      <div class="flex flex-col md:flex-row gap-4">
                         <!-- Note Block -->
                         <div class="flex-1 bg-[#F8F9FA] rounded-2xl p-4 text-sm text-slate-600 font-medium italic">
                           {{ log.nota }}
                         </div>
                         
                         <!-- User Block floating right -->
                         <div class="flex items-center gap-3 self-center md:self-end h-full">
                            <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-[9px] font-bold tracking-wider">
                               {{ log.user?.name ? log.user.name.substring(0,2).toUpperCase() : 'SI' }}
                            </div>
                            <span class="text-xs text-slate-500 font-medium">{{ log.user?.name || 'Sistema Auto.' }}</span>
                         </div>
                      </div>
                   </div>

                </div>
              </div>

              <div v-if="caso.estados_historicos?.length === 0" class="text-center py-16 bg-slate-50 rounded-3xl mt-4">
                 <h4 class="text-slate-600 font-bold">Sin historial registrado</h4>
                 <p class="text-slate-400 text-sm mt-1">Este siniestro aún no tiene actualizaciones de estado.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<style scoped>
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.animate-fade-in-up {
  animation: fadeInUp 0.5s ease-out forwards;
}
</style>
