<script setup>
import { ref, computed } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

// Estado del formulario
const formData = ref({
  eventName: '',
  place: '',
  description: '',
  company: 'Empresa A',
  participants: '',
  provider: '',
  assignedAmount: 5000,
  cost: '',
  spent: '',
  observations: '',
  justificationFile: null
});

// Opciones de empresas
const companies = ref([
  'Empresa A',
  'Empresa B',
  'Empresa C',
  'Empresa D'
]);

// Computed para calcular la diferencia
const difference = computed(() => {
  const assigned = parseFloat(formData.value.assignedAmount) || 0;
  const spent = parseFloat(formData.value.spent) || 0;
  return assigned - spent;
});

// Función para manejar la subida de archivos
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    if (file.type === 'application/pdf') {
      formData.value.justificationFile = file;
    } else {
      alert('Por favor, selecciona un archivo PDF válido');
      event.target.value = '';
    }
  }
};

// Función para eliminar archivo
const removeFile = () => {
  formData.value.justificationFile = null;
  const fileInput = document.getElementById('justification-file');
  if (fileInput) {
    fileInput.value = '';
  }
};

// Función para enviar justificación
const submitJustification = () => {
  // Validación básica
  if (!formData.value.eventName || !formData.value.place || !formData.value.description) {
    alert('Por favor, completa todos los campos obligatorios');
    return;
  }

  if (!formData.value.justificationFile) {
    alert('Por favor, sube un archivo de justificación');
    return;
  }

  console.log('Enviar justificación:', formData.value);
  
  // Aquí implementarías la lógica para enviar
  alert('Justificación enviada correctamente');
  
  // Limpiar formulario
  formData.value = {
    eventName: '',
    place: '',
    description: '',
    company: 'Empresa A',
    participants: '',
    provider: '',
    assignedAmount: 5000,
    cost: '',
    spent: '',
    observations: '',
    justificationFile: null
  };
};

// Función para formatear moneda
const formatCurrency = (amount) => {
  return new Intl.NumberFormat('es-MX', {
    style: 'currency',
    currency: 'USD'
  }).format(amount);
};
</script>

<template>
  <div class="p-6 max-w-auto mx-auto">
    <!-- Header -->
    <div class="flex items-start justify-between gap-4">
      <div>
        <h1 class="text-4xl font-extrabold text-gray-900 dark:text-primary-dt">Justificación de Gastos</h1>
        <p class="mt-1 text-sm text-gray-500 dark:text-primary-dt/70">Documenta y justifica los gastos realizados en eventos</p>
      </div>
    </div>

    <!-- Card principal -->
    <section class="mt-6 bg-white rounded-lg shadow-sm p-6 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt">
      
      <!-- Formulario -->
      <form @submit.prevent="submitJustification" class="space-y-6">
        
        <!-- Detalles del Evento -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          
          <!-- Nombre del Evento -->
          <div class="md:col-span-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Nombre del Evento *
            </label>
            <input
              v-model="formData.eventName"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="Ingresa el nombre del evento"
            >
          </div>

          <!-- Lugar -->
          <div class="md:col-span-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Lugar *
            </label>
            <input
              v-model="formData.place"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="Ingresa el lugar del evento"
            >
          </div>

        </div>

        <!-- Descripción -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
            Descripción y Detalles *
          </label>
          <textarea
            v-model="formData.description"
            required
            rows="4"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent resize-vertical dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
            placeholder="Describe los detalles del evento y los gastos realizados"
          ></textarea>
        </div>

        <!-- Detalles Financieros y Participantes -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          
          <!-- Empresa -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Empresa
            </label>
            <select
              v-model="formData.company"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
            >
              <option v-for="company in companies" :key="company" :value="company">
                {{ company }}
              </option>
            </select>
          </div>

          <!-- Número de Participantes -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Número de Participantes
            </label>
            <input
              v-model.number="formData.participants"
              type="number"
              min="1"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="0"
            >
          </div>

          <!-- Proveedor -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Proveedor
            </label>
            <input
              v-model="formData.provider"
              type="text"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="Nombre del proveedor"
            >
          </div>

          <!-- Monto Asignado -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Monto Asignado (USD)
            </label>
            <input
              v-model.number="formData.assignedAmount"
              type="number"
              min="0"
              step="0.01"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="0.00"
            >
          </div>

          <!-- Costo -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Costo (USD)
            </label>
            <input
              v-model.number="formData.cost"
              type="number"
              min="0"
              step="0.01"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="0.00"
            >
          </div>

          <!-- Gastado -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
              Gastado (USD)
            </label>
            <input
              v-model.number="formData.spent"
              type="number"
              min="0"
              step="0.01"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
              placeholder="0.00"
            >
          </div>

        </div>

        <!-- Resumen financiero -->
        <div v-if="formData.assignedAmount > 0 || formData.spent > 0" class="p-4 bg-gray-50 rounded-lg dark:bg-primary/5">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center">
              <div class="text-sm text-gray-500 dark:text-primary-dt/70">Monto Asignado</div>
              <div class="text-lg font-bold text-blue-600 dark:text-blue-400">
                {{ formatCurrency(formData.assignedAmount) }}
              </div>
            </div>
            <div class="text-center">
              <div class="text-sm text-gray-500 dark:text-primary-dt/70">Gastado</div>
              <div class="text-lg font-bold text-red-600 dark:text-red-400">
                {{ formatCurrency(formData.spent) }}
              </div>
            </div>
            <div class="text-center">
              <div class="text-sm text-gray-500 dark:text-primary-dt/70">Diferencia</div>
              <div class="text-lg font-bold" :class="difference >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'">
                {{ formatCurrency(difference) }}
              </div>
            </div>
          </div>
        </div>

        <!-- Observaciones -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
            Observaciones
          </label>
          <textarea
            v-model="formData.observations"
            rows="3"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:border-transparent resize-vertical dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
            placeholder="Agrega observaciones adicionales si es necesario"
          ></textarea>
        </div>

        <!-- Subida de archivo -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
            Subir justificante (PDF) *
          </label>
          
          <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-[#7c3aed] transition-colors dark:border-primary/20 dark:hover:border-[#7c3aed]">
            <div class="space-y-1 text-center">
              <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
              <div class="flex text-sm text-gray-600 dark:text-primary-dt/70">
                <label for="justification-file" class="relative cursor-pointer bg-white rounded-md font-medium text-[#7c3aed] hover:text-[#6d28d9] focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-[#7c3aed]">
                  <span>Sube un archivo</span>
                  <input
                    id="justification-file"
                    name="justification-file"
                    type="file"
                    accept=".pdf"
                    class="sr-only"
                    @change="handleFileUpload"
                  >
                </label>
                <p class="pl-1">o arrastra y suelta</p>
              </div>
              <p class="text-xs text-gray-500 dark:text-primary-dt/50">
                PDF hasta 10MB
              </p>
            </div>
          </div>

          <!-- Archivo seleccionado -->
          <div v-if="formData.justificationFile" class="mt-3 p-3 bg-green-50 border border-green-200 rounded-lg dark:bg-green-900/20 dark:border-green-800">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <GoogleIcon class="text-green-600 dark:text-green-400 text-xl" name="picture_as_pdf" />
                <span class="text-sm font-medium text-green-800 dark:text-green-300">
                  {{ formData.justificationFile.name }}
                </span>
              </div>
              <button
                @click="removeFile"
                type="button"
                class="text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"
              >
                <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="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>

        <!-- Botón de envío -->
        <div class="flex justify-end pt-6 border-t border-gray-100 dark:border-primary/20">
          <button
            type="submit"
            class="inline-flex items-center gap-2 px-6 py-3 rounded-lg bg-[#7c3aed] hover:bg-[#6d28d9] text-white font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-[#7c3aed] focus:ring-offset-2 transition-colors"
          >
            <GoogleIcon class="text-white text-xl" name="send" />
            Enviar Justificación
          </button>
        </div>

      </form>

    </section>
  </div>
</template>
