<script setup>
import { ref, computed, onMounted } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import VueApexCharts from 'vue3-apexcharts';

// Datos del dashboard
const dashboardData = ref({
  annualBudget: 50000,
  justifiedExpenses: 32500,
  remainingBalance: 17500,
  expenseDistribution: [
    { name: 'Catering', value: 45, color: '#3B82F6' },
    { name: 'Marketing', value: 25, color: '#EF4444' },
    { name: 'Viáticos', value: 15, color: '#F97316' },
    { name: 'Otros', value: 10, color: '#6B7280' },
    { name: 'Renta de Equipo', value: 5, color: '#10B981' }
  ]
});

// Configuración del gráfico de pie
const chartOptions = ref({
  chart: {
    type: 'pie',
    height: 400,
    fontFamily: 'Inter, sans-serif'
  },
  labels: dashboardData.value.expenseDistribution.map(item => item.name),
  colors: dashboardData.value.expenseDistribution.map(item => item.color),
  dataLabels: {
    enabled: true,
    formatter: function (val) {
      return val + "%"
    },
    style: {
      fontSize: '14px',
      fontWeight: 'bold',
      colors: ['#fff']
    }
  },
  legend: {
    position: 'bottom',
    horizontalAlign: 'center',
    fontSize: '14px',
    fontFamily: 'Inter, sans-serif',
    markers: {
      width: 12,
      height: 12,
      radius: 2
    },
    itemMargin: {
      horizontal: 10,
      vertical: 5
    }
  },
  plotOptions: {
    pie: {
      donut: {
        size: '0%'
      },
      expandOnClick: false
    }
  },
  tooltip: {
    y: {
      formatter: function (val) {
        return val + "%"
      }
    }
  },
  responsive: [{
    breakpoint: 768,
    options: {
      chart: {
        height: 300
      },
      legend: {
        position: 'bottom'
      }
    }
  }]
});

// Datos del gráfico
const chartSeries = computed(() => {
  return dashboardData.value.expenseDistribution.map(item => item.value);
});

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

// Función para calcular porcentaje
const calculatePercentage = (value, total) => {
  return ((value / total) * 100).toFixed(1);
};

// Computed para el porcentaje de gastos
const expensesPercentage = computed(() => {
  return calculatePercentage(dashboardData.value.justifiedExpenses, dashboardData.value.annualBudget);
});

// Computed para el porcentaje de saldo restante
const remainingPercentage = computed(() => {
  return calculatePercentage(dashboardData.value.remainingBalance, dashboardData.value.annualBudget);
});

onMounted(() => {
  // Aquí podrías cargar datos reales desde tu API
  console.log('Dashboard de eventos cargado');
});
</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">Dashboard de Eventos</h1>
        <p class="mt-1 text-sm text-gray-500 dark:text-primary-dt/70">Resumen financiero y distribución de gastos por concepto</p>
      </div>
    </div>

    <!-- Tarjetas de métricas -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
      
      <!-- Presupuesto Anual -->
      <div class="bg-white rounded-lg shadow-sm p-6 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-sm font-medium text-gray-500 dark:text-primary-dt/70">Presupuesto Anual</h3>
            <p class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">
              {{ formatCurrency(dashboardData.annualBudget) }}
            </p>
          </div>
          <div class="flex-shrink-0">
            <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center dark:bg-blue-900/30">
              <GoogleIcon class="text-blue-600 dark:text-blue-400 text-xl" name="account_balance_wallet" />
            </div>
          </div>
        </div>
      </div>

      <!-- Gastos Justificados -->
      <div class="bg-white rounded-lg shadow-sm p-6 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-sm font-medium text-gray-500 dark:text-primary-dt/70">Gastos Justificados</h3>
            <p class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">
              {{ formatCurrency(dashboardData.justifiedExpenses) }}
            </p>
            <p class="mt-1 text-xs text-gray-500 dark:text-primary-dt/50">
              {{ expensesPercentage }}% del presupuesto
            </p>
          </div>
          <div class="flex-shrink-0">
            <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center dark:bg-green-900/30">
              <GoogleIcon class="text-green-600 dark:text-green-400 text-xl" name="check_circle" />
            </div>
          </div>
        </div>
      </div>

      <!-- Saldo Restante -->
      <div class="bg-white rounded-lg shadow-sm p-6 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-sm font-medium text-gray-500 dark:text-primary-dt/70">Saldo Restante</h3>
            <p class="mt-2 text-3xl font-bold text-amber-600 dark:text-amber-400">
              {{ formatCurrency(dashboardData.remainingBalance) }}
            </p>
            <p class="mt-1 text-xs text-gray-500 dark:text-primary-dt/50">
              {{ remainingPercentage }}% del presupuesto
            </p>
          </div>
          <div class="flex-shrink-0">
            <div class="w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center dark:bg-amber-900/30">
              <GoogleIcon class="text-amber-600 dark:text-amber-400 text-xl" name="savings" />
            </div>
          </div>
        </div>
      </div>

    </div>

    <!-- Gráfica de distribución -->
    <div class="mt-6 bg-white rounded-lg shadow-sm p-6 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt">
      
      <!-- Título de la sección -->
      <div class="mb-6">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-primary-dt">
          Distribución de Gastos por Concepto
        </h2>
        <p class="mt-1 text-sm text-gray-500 dark:text-primary-dt/70">
          Porcentaje de gastos por categoría
        </p>
      </div>

      <!-- Gráfico de pie -->
      <div class="flex flex-col lg:flex-row gap-6">
        
        <!-- Gráfico -->
        <div class="flex-1">
          <VueApexCharts
            type="pie"
            :options="chartOptions"
            :series="chartSeries"
            height="400"
          />
        </div>

        <!-- Leyenda detallada -->
        <div class="lg:w-80">
          <div class="space-y-3">
            <h3 class="text-lg font-medium text-gray-800 dark:text-primary-dt mb-4">
              Detalle por Categoría
            </h3>
            
            <div
              v-for="(item, index) in dashboardData.expenseDistribution"
              :key="item.name"
              class="flex items-center justify-between p-3 rounded-lg border border-gray-100 dark:border-primary/20"
            >
              <div class="flex items-center gap-3">
                <div 
                  class="w-4 h-4 rounded"
                  :style="{ backgroundColor: item.color }"
                ></div>
                <span class="text-sm font-medium text-gray-700 dark:text-primary-dt">
                  {{ item.name }}
                </span>
              </div>
              <div class="text-right">
                <div class="text-sm font-bold text-gray-900 dark:text-primary-dt">
                  {{ item.value }}%
                </div>
                <div class="text-xs text-gray-500 dark:text-primary-dt/50">
                  {{ formatCurrency((item.value / 100) * dashboardData.justifiedExpenses) }}
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>

      <!-- Resumen estadístico -->
      <div class="mt-6 pt-6 border-t border-gray-100 dark:border-primary/20">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="text-center">
            <div class="text-2xl font-bold text-gray-900 dark:text-primary-dt">
              {{ dashboardData.expenseDistribution.length }}
            </div>
            <div class="text-sm text-gray-500 dark:text-primary-dt/70">
              Categorías
            </div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-gray-900 dark:text-primary-dt">
              {{ Math.max(...dashboardData.expenseDistribution.map(item => item.value)) }}%
            </div>
            <div class="text-sm text-gray-500 dark:text-primary-dt/70">
              Mayor gasto
            </div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-gray-900 dark:text-primary-dt">
              {{ Math.min(...dashboardData.expenseDistribution.map(item => item.value)) }}%
            </div>
            <div class="text-sm text-gray-500 dark:text-primary-dt/70">
              Menor gasto
            </div>
          </div>
        </div>
      </div>

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