<template>
  <div class="admin-dashboard">
    <div class="dashboard-header">
      <div class="header-main">
        <button class="back-btn" @click="router.push('/admin')">
          <span class="material-icons">arrow_back</span>
        </button>
        <div>
          <h1>Análisis Estratégico</h1>
          <p class="subtitle">Métricas en tiempo real del ecosistema SIBU</p>
        </div>
      </div>
      <div class="header-actions">
        <div v-if="lastRefreshed" class="last-sync">
          Actualizado: {{ lastRefreshed }}
        </div>
        <button class="refresh-action" @click="loadStats" :disabled="isLoading">
          <span class="material-icons" :class="{ 'spin': isLoading }">refresh</span>
          {{ isLoading ? 'Sincronizando...' : 'Refrescar' }}
        </button>
      </div>
    </div>

    <div v-if="isLoading && !stats.total_events" class="loading-overlay">
      <div class="loader-content">
        <div class="spinner"></div>
        <p>Procesando datos...</p>
      </div>
    </div>

    <div v-else class="dashboard-grid">
      <!-- Top Overview Metrics -->
      <div class="metrics-row">
        <div class="metric-card primary">
          <div class="card-icon"><span class="material-icons">analytics</span></div>
          <div class="card-info">
            <label>Eventos Totales</label>
            <h3>{{ stats.total_events?.toLocaleString() || '0' }}</h3>
          </div>
        </div>
        <div class="metric-card">
          <div class="card-icon"><span class="material-icons">speed</span></div>
          <div class="card-info">
            <label>Pico de Actividad</label>
            <h3>{{ stats.peak_hours?.[0]?.hour || '--' }}:00</h3>
          </div>
        </div>
        <div class="metric-card">
          <div class="card-icon"><span class="material-icons">visibility</span></div>
          <div class="card-info">
            <label>Pantalla Principal</label>
            <h3>{{ stats.screen_activity?.[0]?.name || 'Mapa' }}</h3>
          </div>
        </div>
      </div>

      <!-- Charts Rows -->
      <div class="stats-row">
        <div class="chart-box flex-66">
          <div class="box-header">
            <h3>Tendencia de Uso (Últimos 7 días)</h3>
          </div>
          <div class="chart-container">
            <Line v-if="trendChartData" :data="trendChartData" :options="chartOptions" />
          </div>
        </div>

        <div class="chart-box flex-33">
          <div class="box-header">
            <h3>Distribución por Idioma</h3>
          </div>
          <div class="chart-container circle">
            <Doughnut v-if="langChartData" :data="langChartData" :options="doughnutOptions" />
          </div>
        </div>
      </div>

      <div class="stats-row">
        <div class="chart-box flex-50">
          <div class="box-header">
            <h3>Popularidad de Rutas</h3>
          </div>
          <div class="chart-container">
            <Bar v-if="routesChartData" :data="routesChartData" :options="chartOptions" />
          </div>
        </div>

        <div class="chart-box flex-50">
          <div class="box-header">
            <h3>Visualizaciones de Promociones</h3>
          </div>
          <div class="chart-container">
            <Bar v-if="promosChartData" :data="promosChartData" :options="horizontalBarOptions" />
          </div>
        </div>
      </div>

      <div class="stats-row">
        <div class="chart-box flex-50">
          <div class="box-header">
            <h3>Top Acciones (Taxis/Otros)</h3>
          </div>
          <div class="plain-list">
            <div v-for="(taxi, idx) in stats.top_taxis" :key="idx" class="list-row">
              <span class="rank">{{ Number(idx) + 1 }}</span>
              <span class="label">{{ taxi.id || 'N/A' }}</span>
              <span class="val">{{ taxi.count }}</span>
            </div>
            <p v-if="!stats.top_taxis?.length" class="empty">Sin registros</p>
          </div>
        </div>

        <div class="chart-box flex-50">
          <div class="box-header">
            <h3>Top Paradas</h3>
          </div>
          <div class="plain-list">
            <div v-for="(stop, idx) in stats.top_stops" :key="idx" class="list-row">
              <span class="rank">{{ Number(idx) + 1 }}</span>
              <span class="label">{{ stop.id || 'N/A' }}</span>
              <span class="val">{{ stop.count }}</span>
            </div>
            <p v-if="!stats.top_stops?.length" class="empty">Sin registros</p>
          </div>
        </div>
      </div>

      <div class="stats-row">
        <div class="chart-box flex-100">
          <div class="box-header">
            <h3>Actividad por Hora</h3>
          </div>
          <div class="chart-container">
            <Bar v-if="hoursChartData" :data="hoursChartData" :options="chartOptions" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import { analyticsService } from '@/services/analyticsService'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement
} from 'chart.js'
import { Line, Bar, Doughnut } from 'vue-chartjs'

// Register ChartJS
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend
)

const isLoading = ref(true)
const stats = ref<any>({})
const lastRefreshed = ref('')

async function loadStats() {
  isLoading.value = true
  try {
    stats.value = await analyticsService.getStats()
    lastRefreshed.value = new Date().toLocaleTimeString()
  } catch (e) {
    console.error('Error loading stats')
  } finally {
    isLoading.value = false
  }
}

// Chart Configurations
const chartOptions = computed<any>(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false }
  },
  scales: {
    y: {
      beginAtZero: true,
      grid: { color: 'rgba(255, 255, 255, 0.05)' },
      ticks: { color: 'rgba(255, 255, 255, 0.5)' }
    },
    x: {
      grid: { display: false },
      ticks: { color: 'rgba(255, 255, 255, 0.5)' }
    }
  }
}))

const horizontalBarOptions = computed<any>(() => ({
  indexAxis: 'y' as const,
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false }
  },
  scales: {
    x: {
      beginAtZero: true,
      grid: { color: 'rgba(255, 255, 255, 0.05)' },
      ticks: { color: 'rgba(255, 255, 255, 0.5)' }
    },
    y: {
      grid: { display: false },
      ticks: { color: 'rgba(255, 255, 255, 0.5)' }
    }
  }
}))

const doughnutOptions = computed<any>(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'bottom',
      labels: { color: '#fff', padding: 20 }
    }
  }
}))

// Computed Chart Data
const trendChartData = computed<any>(() => {
  if (!stats.value.daily_trends?.length) return null
  return {
    labels: stats.value.daily_trends.map((t: any) => t.date.split('-').slice(1).join('/')),
    datasets: [{
      label: 'Eventos',
      data: stats.value.daily_trends.map((t: any) => t.count),
      borderColor: '#fee715',
      backgroundColor: 'rgba(254, 231, 21, 0.1)',
      fill: true,
      tension: 0.4
    }]
  }
})

const langChartData = computed<any>(() => {
  if (!stats.value.languages?.length) return null
  return {
    labels: stats.value.languages.map((l: any) => l.id === 'es' ? 'Español' : 'English'),
    datasets: [{
      data: stats.value.languages.map((l: any) => l.count),
      backgroundColor: ['#fee715', '#64748b'],
      borderWidth: 0
    }]
  }
})

const promosChartData = computed<any>(() => {
  if (!stats.value.top_promos?.length) return null
  return {
    labels: stats.value.top_promos.map((p: any) => p.id),
    datasets: [{
      label: 'Visualizaciones',
      data: stats.value.top_promos.map((p: any) => p.count),
      backgroundColor: '#fee715',
      borderRadius: 6
    }]
  }
})

const routesChartData = computed<any>(() => {
  if (!stats.value.top_routes?.length) return null
  return {
    labels: stats.value.top_routes.map((r: any) => r.id),
    datasets: [{
      label: 'Consultas',
      data: stats.value.top_routes.map((r: any) => r.count),
      backgroundColor: '#fee715',
      borderRadius: 8
    }]
  }
})

const hoursChartData = computed<any>(() => {
  if (!stats.value.peak_hours?.length) return null
  // Sort by hour
  const sorted = [...stats.value.peak_hours].sort((a,b) => a.hour - b.hour)
  return {
    labels: sorted.map(h => `${h.hour}h`),
    datasets: [{
      label: 'Actividad',
      data: sorted.map(h => h.count),
      backgroundColor: 'rgba(254, 231, 21, 0.2)',
      hoverBackgroundColor: '#fee715',
      borderRadius: 4
    }]
  }
})

onMounted(loadStats)
</script>

<style scoped>
.admin-dashboard {
    padding: 32px 24px;
    max-width: 1400px;
    margin: 0 auto;
    min-height: 100vh;
    padding-bottom: 120px;
}

.dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 48px;
    gap: 24px;
}

.header-main {
    display: flex;
    align-items: center;
    gap: 20px;
}

.back-btn {
    background: var(--hover-bg);
    border: 1px solid var(--border-color);
    width: 44px;
    height: 44px;
    border-radius: 14px;
    cursor: pointer;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}

.back-btn:hover { background: var(--active-color); color: #101820; transform: scale(1.05); }

h1 { 
    font-size: clamp(2rem, 5vw, 2.5rem); 
    font-weight: 900; 
    margin: 0; 
    background: linear-gradient(135deg, #fee715 0%, #facc15 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: -0.04em;
}

.subtitle { color: var(--text-secondary); margin: 6px 0 0 0; font-weight: 500; }

.header-actions {
  display: flex;
  align-items: center;
  gap: 24px;
}

.last-sync { font-size: 13px; color: var(--text-secondary); font-weight: 600; }

.refresh-action {
  background: linear-gradient(135deg, #fee715 0%, #facc15 100%);
  color: #101820;
  border: none;
  padding: 12px 24px;
  border-radius: 14px;
  font-weight: 900;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: all 0.3s;
  box-shadow: 0 10px 20px rgba(254, 231, 21, 0.2);
}

.refresh-action:hover { transform: translateY(-2px); box-shadow: 0 15px 30px rgba(254, 231, 21, 0.3); }
.refresh-action:disabled { opacity: 0.5; cursor: not-allowed; }

.spin { animation: rotation 1s infinite linear; }
@keyframes rotation { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

/* Metrics */
.metrics-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.metric-card {
  background: var(--card-bg);
  backdrop-filter: blur(12px);
  padding: 28px;
  border-radius: 28px;
  display: flex;
  align-items: center;
  gap: 24px;
  border: 1px solid var(--border-color);
  transition: all 0.3s;
}

.metric-card:hover { transform: translateY(-4px); border-color: var(--active-color); }

.metric-card.primary {
  background: linear-gradient(135deg, #fee715 0%, #facc15 100%);
  color: #101820;
  border: none;
}

.card-icon {
  width: 60px;
  height: 60px;
  background: rgba(255,255,255,0.05);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.metric-card.primary .card-icon { background: rgba(0,0,0,0.1); }

.card-icon .material-icons { font-size: 32px; color: var(--active-color); }
.metric-card.primary .card-icon .material-icons { color: #101820; }

.card-info label { display: block; font-size: 13px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.1em; font-weight: 800; margin-bottom: 4px; }
.metric-card.primary .card-info label { color: #101820; opacity: 0.7; }
.card-info h3 { font-size: 28px; font-weight: 900; margin: 0; letter-spacing: -0.02em; }

/* Charts */
.dashboard-grid {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.chart-box {
  background: var(--card-bg);
  backdrop-filter: blur(12px);
  border-radius: 32px;
  padding: 32px;
  border: 1px solid var(--border-color);
}

.box-header { margin-bottom: 32px; }
.box-header h3 { font-size: 1.25rem; font-weight: 900; color: var(--text-primary); display: flex; align-items: center; gap: 12px; letter-spacing: -0.02em; }

.chart-container { height: 320px; position: relative; }
.chart-container.circle { height: 280px; }

.stats-row {
  display: flex;
  gap: 32px;
}

.flex-33 { flex: 1; }
.flex-50 { flex: 1; }
.flex-66 { flex: 2; }
.flex-100 { flex: 1; width: 100%; }

/* Plain Lists */
.plain-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.list-row {
  display: flex;
  align-items: center;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: 16px;
  border: 1px solid var(--border-color);
  transition: all 0.3s;
}

.list-row:hover { transform: translateX(8px); border-color: var(--active-color); }

.rank { width: 32px; color: var(--text-secondary); font-weight: 900; font-size: 14px; }
.label { flex: 1; font-weight: 700; color: var(--text-primary); }
.val { font-weight: 900; color: var(--active-color); font-size: 1.1rem; }

.empty { text-align: center; color: var(--text-secondary); padding: 48px; font-weight: 600; }

.loading-overlay {
  height: 60vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loader-content { text-align: center; }
.spinner {
  width: 60px;
  height: 60px;
  border: 4px solid var(--border-color);
  border-top-color: var(--active-color);
  border-radius: 50%;
  animation: rotation 1s infinite linear;
  margin: 0 auto 24px;
}

@media (max-width: 768px) {
  .stats-row { flex-direction: column; }
  .metrics-row { grid-template-columns: 1fr; }
  .dashboard-header { flex-direction: column; align-items: flex-start; }
}
</style>
