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

// Estado del presupuesto
const budgetItems = ref([
  {
    id: 1,
    concept: 'Ej. Catering para evento X',
    amount: 1500.00
  },
]);

let nextId = 5;

// Computed para calcular el total
const totalBudget = computed(() => {
  return budgetItems.value.reduce((total, item) => {
    return total + (parseFloat(item.amount) || 0);
  }, 0);
});

// Función para agregar nueva fila
const addBudgetItem = () => {
  budgetItems.value.push({
    id: nextId++,
    concept: '',
    amount: 0
  });
};

// Función para eliminar fila
const removeBudgetItem = (id) => {
  if (budgetItems.value.length > 1) {
    budgetItems.value = budgetItems.value.filter(item => item.id !== id);
  }
};

// Función para guardar presupuesto
const saveBudget = () => {
  // Filtrar elementos vacíos
  const validItems = budgetItems.value.filter(item => 
    item.concept.trim() !== '' && item.amount > 0
  );

  if (validItems.length === 0) {
    alert('Por favor, agrega al menos un elemento al presupuesto');
    return;
  }

  console.log('Guardar presupuesto:', {
    items: validItems,
    total: totalBudget.value
  });

  // Aquí implementarías la lógica para guardar
  alert(`Presupuesto guardado correctamente. Total: $${totalBudget.value.toFixed(2)}`);
};

// 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">Asignación de Presupuesto Anual</h1>
        <p class="mt-1 text-sm text-gray-500 dark:text-primary-dt/70">Gestiona y asigna el presupuesto anual para eventos y actividades</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 de presupuesto -->
      <div class="space-y-6">
        
        <!-- Filas de presupuesto -->
        <div class="space-y-4">
          <div
            v-for="(item, index) in budgetItems"
            :key="item.id"
            class="grid grid-cols-1 md:grid-cols-12 gap-4 items-end"
          >
            
            <!-- Campo Concepto -->
            <div class="md:col-span-5">
              <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
                Concepto
              </label>
              <input
                v-model="item.concept"
                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-[#2563eb] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
                :placeholder="index === 0 ? 'Ej. Catering para evento X' : 'Ingresa el concepto'"
              >
            </div>

            <!-- Campo Monto -->
            <div class="md:col-span-4">
              <label class="block text-sm font-medium text-gray-700 dark:text-primary-dt mb-2">
                Monto (USD)
              </label>
              <input
                v-model.number="item.amount"
                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-[#2563eb] focus:border-transparent dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
                placeholder="0.00"
              >
            </div>

            <!-- Botón de eliminar -->
            <div class="md:col-span-3 flex justify-end">
              <button
                v-if="budgetItems.length > 1"
                @click="removeBudgetItem(item.id)"
                type="button"
                class="p-2 text-red-500 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors dark:text-red-400 dark:hover:text-red-300 dark:hover:bg-red-900/20"
                title="Eliminar fila"
              >
                <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </div>

          </div>
        </div>

        <!-- Resumen del presupuesto -->
        <div class="mt-8 p-4 bg-gray-50 rounded-lg dark:bg-primary/5">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <GoogleIcon class="text-gray-600 dark:text-primary-dt text-xl" name="account_balance_wallet" />
              <span class="text-lg font-medium text-gray-800 dark:text-primary-dt">Total del Presupuesto:</span>
            </div>
            <div class="text-2xl font-bold text-[#2563eb] dark:text-primary-dt">
              {{ formatCurrency(totalBudget) }}
            </div>
          </div>
        </div>

        <!-- Botones de acción -->
        <div class="flex items-center justify-between pt-6 border-t border-gray-100 dark:border-primary/20">
          
          <!-- Botón Agregar más -->
          <button
            @click="addBudgetItem"
            type="button"
            class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-green-600 hover:bg-green-700 text-white font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
          >
            <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="M12 4v16M20 12H4"></path>
            </svg>
            + Agregar más
          </button>

          <!-- Botón Guardar Presupuesto -->
          <button
            @click="saveBudget"
            type="button"
            class="inline-flex items-center gap-2 px-6 py-2 rounded-lg bg-[#2563eb] hover:bg-[#1e40af] text-white font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-[#2563eb] focus:ring-offset-2 transition-colors"
          >
            <GoogleIcon class="text-white text-xl" name="save" />
            Guardar Presupuesto
          </button>

        </div>

      </div>

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