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

const props = defineProps({
  title: String,
  caso: Object,
  proveedores: Array,
  ejecutivos: Array,
  directores: Array,
  reinspectores: Array,
});

const form = useForm({
  ejecutivo_id: props.caso.ejecutivo_id || '',
  director_id: props.caso.director_id || '',
  reinspector_id: props.caso.reinspector_id || '',
  proveedor_id: '',
  tipo_compra: 'stock',
  tipo_compra_taller: props.caso.tipo_compra_taller || '',
  observaciones: '',
  items: [{ repuesto: '', cantidad: 1, precio_unitario: 0 }],
});

const notifForm = useForm({
  tipo: 'stock',
  notificar_a: ['cliente', 'broker']
});

const imparForm = useForm({
  recepcion_impar: props.caso.recepcion_impar ?? null,
  cuadro_comparativo: null,
});

const submitting = ref(false);

const submitGrabar = () => {
  submitting.value = true;
  form.post(route('mesa-compras.grabar', props.caso.id), {
    onFinish: () => submitting.value = false
  });
};

const submitNotificar = () => {
  notifForm.post(route('mesa-compras.notificar', props.caso.id));
};

const handleFileChange = (e) => {
    imparForm.cuadro_comparativo = e.target.files[0];
};

const submitUploadCuadro = () => {
    imparForm.post(route('mesa-compras.upload-cuadro', props.caso.id), {
        forceFormData: true,
        preserveScroll: true,
    });
};

const submitRechazoImpar = () => {
    imparForm.post(route('mesa-compras.rechazar-impar', props.caso.id), {
        preserveScroll: true,
    });
};

const submitEnviarAprobacion = () => {
    useForm({}).post(route('mesa-compras.enviar-aprobacion', props.caso.id), {
        preserveScroll: true,
    });
};
</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">
      <!-- Breadcrumbs -->
      <div class="mb-6">
        <Link :href="route('mesa-compras')" class="text-brand-blue hover:underline flex items-center gap-2 text-sm font-medium">
          <font-awesome-icon :icon="['fas', 'arrow-left']" class="w-4 h-4" />
          Volver al Buscador
        </Link>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Panel Izquierdo: Datos del Caso (Slide 6) -->
        <div class="lg:col-span-1 space-y-6">
          <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-6">Datos del Caso</h3>
            
            <div class="space-y-4">
              <div class="flex justify-between">
                <span class="text-xs text-slate-500">Asegurado:</span>
                <span class="text-xs font-bold text-slate-800">{{ caso.cliente?.nombre }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-xs text-slate-500">No. Caso:</span>
                <span class="text-xs font-bold text-slate-800">{{ caso.numero_reclamo }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-xs text-slate-500">Placa:</span>
                <span class="text-xs font-bold text-brand-blue font-mono">{{ caso.vehiculo?.placa }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-xs text-slate-500">Cobertura:</span>
                <span class="text-[10px] font-bold bg-brand-blue text-white px-2 py-0.5 rounded">{{ caso.cobertura }}</span>
              </div>
            </div>

            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mt-8 mb-4">Datos Bróker</h3>
            <div class="space-y-4">
               <div class="text-xs font-bold text-slate-800">{{ caso.broker?.razon_social || 'S/N' }}</div>
               <div class="text-[10px] text-slate-500">{{ caso.broker?.email }}</div>
            </div>

            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mt-8 mb-4">Taller</h3>
            <div class="space-y-4">
               <div class="text-xs font-bold text-slate-800">{{ caso.taller?.razon_social || 'S/N' }}</div>
               <div class="flex flex-col gap-1">
                 <div class="text-[10px] text-slate-500 font-bold uppercase tracking-tighter">Ejecutivo Taller:</div>
                 <div class="text-[11px] font-black text-slate-700 uppercase">{{ caso.taller_ejecutivo || 'No registrado' }}</div>
               </div>
               <div class="text-[10px] text-slate-500">{{ caso.taller?.direccion }}</div>
            </div>
          </div>

          <!-- Acciones de Notificación (Slide 7-9) -->
          <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-6">Notificaciones</h3>
            
            <div class="space-y-4">
              <div>
                <label class="form-label">Tipo de Notificación</label>
                <select v-model="notifForm.tipo" class="form-input text-xs">
                  <option value="stock">Stock</option>
                  <option value="importacion">Importación</option>
                </select>
              </div>

              <div class="flex flex-col gap-2">
                <label class="flex items-center gap-2 cursor-pointer">
                   <input type="checkbox" v-model="notifForm.notificar_a" value="cliente" class="rounded text-brand-blue">
                   <span class="text-xs text-slate-700">Notificar a Cliente</span>
                </label>
                <label class="flex items-center gap-2 cursor-pointer">
                   <input type="checkbox" v-model="notifForm.notificar_a" value="broker" class="rounded text-brand-blue">
                   <span class="text-xs text-slate-700">Notificar a Bróker</span>
                </label>
              </div>

              <button 
                @click="submitNotificar"
                class="w-full py-3 bg-brand-blue text-white rounded-xl font-bold hover:bg-brand-blue/90 transition-all shadow-lg shadow-brand-blue/20 uppercase text-[10px] tracking-widest flex items-center justify-center gap-2"
              >
                <font-awesome-icon :icon="['fas', 'envelope']" class="w-4 h-4" />
                Guardar y Notificar
              </button>
            </div>
          </div>

          <!-- Estado de Aprobación (Slide 7) -->
          <div v-if="caso.token_aprobacion" class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
             <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Estado de Aprobación</h3>
             <div class="flex items-center gap-3 p-4 rounded-xl" 
                :class="caso.aprobacion_estado === 'aceptado' ? 'bg-green-50 text-green-700 border border-green-100' : (caso.aprobacion_estado === 'rechazado' ? 'bg-red-50 text-red-700 border border-red-100' : 'bg-amber-50 text-amber-700 border border-amber-100')"
             >
                <div class="w-2 h-2 rounded-full animate-pulse" :class="caso.aprobacion_estado === 'aceptado' ? 'bg-green-600' : (caso.aprobacion_estado === 'rechazado' ? 'bg-red-600' : 'bg-amber-600')"></div>
                <span class="text-xs font-bold uppercase tracking-widest">
                    {{ caso.aprobacion_estado === 'aceptado' ? 'ACEPTADO' : (caso.aprobacion_estado === 'rechazado' ? 'RECHAZADO' : 'PENDIENTE DE CLIENTE') }}
                </span>
             </div>
             <p v-if="!caso.aprobacion_estado" class="mt-3 text-[10px] text-slate-500 italic text-center">
                El cliente tiene un link activo para aprobar la importación.
             </p>
          </div>
        </div>

        <!-- Panel Central/Derecho: Gestión de Compra -->
        <div class="lg:col-span-2 space-y-6">
          <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-8">Gestión de Proforma</h3>
            
            <form @submit.prevent="submitGrabar" class="space-y-8">
              <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                   <label class="form-label text-[10px]">Ejecutivo Mesa de Compras *</label>
                   <select v-model="form.ejecutivo_id" class="form-input" required>
                      <option value="">Seleccionar...</option>
                      <option v-for="e in ejecutivos" :key="e.id" :value="e.id">{{ e.nombre }}</option>
                   </select>
                </div>
                <div>
                   <label class="form-label text-[10px]">Director *</label>
                   <select v-model="form.director_id" class="form-input" required>
                      <option value="">Seleccionar...</option>
                      <option v-for="d in directores" :key="d.id" :value="d.id">{{ d.nombre }}</option>
                   </select>
                </div>
                <div>
                   <label class="form-label text-[10px]">Reinspector *</label>
                   <select v-model="form.reinspector_id" class="form-input" required>
                      <option value="">Seleccionar...</option>
                      <option v-for="r in reinspectores" :key="r.id" :value="r.id">{{ r.nombre }}</option>
                   </select>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                 <div>
                    <label class="form-label text-[10px]">Proveedor (Módulo 11) *</label>
                    <select v-model="form.proveedor_id" class="form-input" required>
                       <option value="">Seleccionar Proveedor...</option>
                       <option v-for="p in proveedores" :key="p.id" :value="p.id">{{ p.nombre }} ({{ p.ciudad }})</option>
                    </select>
                 </div>
                <div>
                    <label class="form-label text-[10px]">Tipo de Compra Taller (Slide 6-8) *</label>
                    <select v-model="form.tipo_compra_taller" class="form-input" required>
                        <option value="">Seleccionar Tipo...</option>
                        <option value="dealer">Dealer – repuestos completos</option>
                        <option value="multimarca_dealer">Multimarca – Dealer</option>
                        <option value="multimarca">Multimarca</option>
                        <option value="taller_asegurado">Taller asegurado</option>
                    </select>
                </div>
              </div>

              <div>
                 <label class="form-label">Tipo de Compra *</label>
                 <div class="flex gap-4 mt-2">
                    <label class="px-4 py-2 rounded-xl border border-slate-200 text-xs font-bold cursor-pointer transition-all"
                      :class="form.tipo_compra === 'stock' ? 'bg-brand-blue text-white border-brand-blue' : 'bg-white text-slate-600 hover:border-brand-blue'"
                    >
                       <input type="radio" v-model="form.tipo_compra" value="stock" class="hidden">
                       Stock
                    </label>
                    <label class="px-4 py-2 rounded-xl border border-slate-200 text-xs font-bold cursor-pointer transition-all"
                      :class="form.tipo_compra === 'importacion' ? 'bg-brand-blue text-white border-brand-blue' : 'bg-white text-slate-600 hover:border-brand-blue'"
                    >
                       <input type="radio" v-model="form.tipo_compra" value="importacion" class="hidden">
                       Importación
                    </label>
                 </div>
              </div>

              <!-- Items Section (Module 6 submodule) -->
              <div class="mt-8 border-t border-slate-50 pt-6">
                 <div class="flex justify-between items-center mb-4">
                    <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Repuestos / Ítems Requeridos</label>
                    <button type="button" @click="form.items.push({ repuesto: '', cantidad: 1, precio_unitario: 0 })" class="text-[10px] font-bold text-brand-blue hover:underline">
                       + AGREGAR ÍTEM
                    </button>
                 </div>
                 <div class="overflow-x-auto rounded-xl border border-slate-100 shadow-sm">
                    <table class="w-full text-[10px]">
                       <thead>
                          <tr class="bg-slate-50 text-slate-500 text-left">
                             <th class="p-2 border-b border-slate-200">Repuesto / Descripción</th>
                             <th class="p-2 border-b border-slate-200 w-20 text-center">Cant.</th>
                             <th class="p-2 border-b border-slate-200 w-24 text-center">Acciones</th>
                          </tr>
                       </thead>
                       <tbody>
                          <tr v-for="(item, index) in form.items" :key="index" class="hover:bg-slate-50 transition-colors">
                             <td class="p-0 border-b border-slate-200 border-r">
                                <input v-model="item.repuesto" type="text" class="w-full border-0 p-3 text-xs focus:ring-1 focus:ring-inset focus:ring-brand-blue bg-transparent" placeholder="Ej. Faro delantero derecho">
                             </td>
                             <td class="p-0 border-b border-slate-200 border-r">
                                <input v-model="item.cantidad" type="number" class="w-full border-0 p-3 text-xs text-center focus:ring-1 focus:ring-inset focus:ring-brand-blue bg-transparent">
                             </td>
                             <td class="p-2 border-b border-slate-200 text-center">
                                <button type="button" @click="form.items.splice(index, 1)" class="text-red-400 hover:text-red-600 transition-colors" v-if="form.items.length > 1">
                                   <font-awesome-icon :icon="['fas', 'trash-alt']" />
                                </button>
                             </td>
                          </tr>
                       </tbody>
                    </table>
                 </div>
              </div>

              <div>
                 <label class="form-label">Recepción proforma IMPAR</label>
                 <div class="flex gap-4 mt-2">
                    <label class="px-4 py-2 rounded-xl border border-slate-200 text-xs font-bold cursor-pointer transition-all"
                      :class="imparForm.recepcion_impar === true ? 'bg-brand-blue text-white border-brand-blue' : 'bg-white text-slate-600 hover:border-brand-blue'"
                    >
                       <input type="radio" :value="true" v-model="imparForm.recepcion_impar" class="hidden">
                       Sí
                    </label>
                    <label class="px-4 py-2 rounded-xl border border-slate-200 text-xs font-bold cursor-pointer transition-all"
                      :class="imparForm.recepcion_impar === false ? 'bg-red-500 text-white border-red-500' : 'bg-white text-slate-600 hover:border-red-400'"
                    >
                       <input type="radio" :value="false" v-model="imparForm.recepcion_impar" class="hidden">
                       No
                    </label>
                 </div>
              </div>

              <div v-if="imparForm.recepcion_impar === true" class="p-4 bg-slate-50 border border-slate-100 rounded-xl space-y-4 shadow-inner">
                 <label class="form-label text-slate-700">Cargar Cuadro Comparativo</label>
                 <div class="flex gap-2 items-center">
                     <input type="file" @change="handleFileChange" accept=".pdf,.xls,.xlsx,.doc,.docx,.jpg,.jpeg,.png" class="text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-xs file:font-semibold file:bg-brand-blue file:text-brand-blue hover:file:bg-brand-blue cursor-pointer">
                     <button type="button" @click="submitUploadCuadro" :disabled="!imparForm.cuadro_comparativo" class="px-4 py-2 bg-slate-800 text-white rounded-xl text-[10px] font-bold uppercase hover:bg-slate-900 transition-all disabled:opacity-50">
                        Subir Archivo
                     </button>
                 </div>
                 <div v-if="caso.cuadro_comparativo_path" class="mt-2 text-xs text-green-600 font-bold flex items-center gap-1">
                     <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="M5 13l4 4L19 7"></path></svg>
                     Cuadro comparativo cargado en sistema.
                 </div>
              </div>

              <div class="flex gap-4 pt-6 border-t border-slate-50 flex-wrap">
                 <button 
                  type="submit" 
                  class="px-8 py-3 bg-brand-blue text-white rounded-xl font-bold hover:bg-brand-blue transition-all shadow-lg shadow-brand-blue uppercase text-xs tracking-widest"
                 >
                    Grabar
                 </button>

                 <div class="flex-1"></div>

                 <!-- Botones dinámicos según Recepción IMPAR -->
                 <button v-if="imparForm.recepcion_impar === false" type="button" @click="submitRechazoImpar" class="px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-xl text-[10px] font-bold uppercase hover:bg-red-100 transition-all">
                    Notificar trabajar con valores de taller
                 </button>

                 <template v-if="imparForm.recepcion_impar === true">
                     <button type="button" @click="submitEnviarAprobacion" :disabled="!caso.cuadro_comparativo_path" class="px-4 py-2 bg-green-600 text-white rounded-xl text-[10px] font-bold uppercase hover:bg-green-700 transition-all disabled:opacity-50 shadow-md">
                        Enviar a Ejecutivo y Reinspector
                     </button>
                 </template>
                 <template v-else-if="imparForm.recepcion_impar === null">
                     <button type="button" class="px-4 py-2 border border-slate-200 text-slate-600 rounded-xl text-[10px] font-bold uppercase hover:bg-slate-50 transition-all">
                        Realizar Cuadro Comparativo
                     </button>
                 </template>
              </div>
            </form>
          </div>

          <!-- Historial de Cotizaciones -->
          <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
             <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-6">Proformas Registradas</h3>
             
             <div class="space-y-4">
                <div v-for="cot in caso.cotizaciones" :key="cot.id" class="p-4 bg-slate-50 rounded-xl border border-slate-100 flex justify-between items-center">
                   <div>
                      <div class="text-xs font-bold text-slate-800">{{ cot.proveedor?.nombre }}</div>
                      <div class="text-[10px] text-slate-500 uppercase">{{ cot.tipo }} | {{ cot.estado }}</div>
                   </div>
                   <div class="text-[10px] font-bold text-slate-400">
                      {{ new Date(cot.created_at).toLocaleDateString() }}
                   </div>
                </div>
                <div v-if="caso.cotizaciones?.length === 0" class="text-center py-6 text-slate-400 italic text-sm">
                   No hay proformas registradas aún.
                </div>
             </div>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>
