<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { BarChart3, TrendingUp, Users, Clock, Download } from 'lucide-vue-next'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { useApi } from '@/composables/useApi'
import type { AnalyticsSummary, TimeseriesData } from '@/types'

const api = useApi()

const timeRange = ref<'24h' | '7d' | '30d'>('7d')
const loading = ref(true)
const summary = ref<AnalyticsSummary | null>(null)
const timeseries = ref<TimeseriesData | null>(null)

const playerChart = ref<HTMLElement | null>(null)
const perfChart = ref<HTMLElement | null>(null)
let playerChartInstance: ECharts | null = null
let perfChartInstance: ECharts | null = null

const rangeToHours = (range: string): number => {
  switch (range) {
    case '24h': return 24
    case '7d': return 168
    case '30d': return 720
    default: return 168
  }
}

const loadAnalytics = async () => {
  loading.value = true
  try {
    const hours = rangeToHours(timeRange.value)

    const [summaryRes, timeseriesRes] = await Promise.all([
      api.get<AnalyticsSummary>(`/api/analytics/summary?range=${hours}`),
      api.get<TimeseriesData>(`/api/analytics/timeseries?range=${hours}&granularity=hourly`)
    ])

    summary.value = summaryRes
    timeseries.value = timeseriesRes

    await nextTick()
    renderCharts()
  } catch (error) {
    console.error('Failed to load analytics:', error)
  } finally {
    loading.value = false
  }
}

const renderCharts = () => {
  if (!timeseries.value) return

  // Player count chart
  if (playerChart.value) {
    if (playerChartInstance) {
      playerChartInstance.dispose()
    }
    playerChartInstance = echarts.init(playerChart.value)

    playerChartInstance.setOption({
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#1a1a1a',
        borderColor: '#2a2a2a',
        textStyle: { color: '#e5e5e5' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeseries.value.timestamps.map(ts => new Date(ts).toLocaleString('en-US', {
          month: 'short',
          day: 'numeric',
          hour: '2-digit'
        })),
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080', rotate: 45 }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#404040' } },
        splitLine: { lineStyle: { color: '#2a2a2a' } },
        axisLabel: { color: '#808080' }
      },
      series: [
        {
          name: 'Players',
          type: 'line',
          data: timeseries.value.player_count,
          smooth: true,
          lineStyle: { color: '#CE422B', width: 2 },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(206, 66, 43, 0.3)' },
              { offset: 1, color: 'rgba(206, 66, 43, 0)' }
            ])
          },
          itemStyle: { color: '#CE422B' }
        }
      ]
    })
  }

  // Performance chart (FPS + Entities)
  if (perfChart.value) {
    if (perfChartInstance) {
      perfChartInstance.dispose()
    }
    perfChartInstance = echarts.init(perfChart.value)

    perfChartInstance.setOption({
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#1a1a1a',
        borderColor: '#2a2a2a',
        textStyle: { color: '#e5e5e5' }
      },
      legend: {
        data: ['FPS', 'Entities'],
        textStyle: { color: '#a3a3a3' },
        top: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeseries.value.timestamps.map(ts => new Date(ts).toLocaleString('en-US', {
          month: 'short',
          day: 'numeric',
          hour: '2-digit'
        })),
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080', rotate: 45 }
      },
      yAxis: [
        {
          type: 'value',
          name: 'FPS',
          position: 'left',
          axisLine: { lineStyle: { color: '#404040' } },
          splitLine: { lineStyle: { color: '#2a2a2a' } },
          axisLabel: { color: '#808080' }
        },
        {
          type: 'value',
          name: 'Entities',
          position: 'right',
          axisLine: { lineStyle: { color: '#404040' } },
          splitLine: { show: false },
          axisLabel: { color: '#808080' }
        }
      ],
      series: [
        {
          name: 'FPS',
          type: 'line',
          yAxisIndex: 0,
          data: timeseries.value.fps,
          smooth: true,
          lineStyle: { color: '#10b981', width: 2 },
          itemStyle: { color: '#10b981' }
        },
        {
          name: 'Entities',
          type: 'line',
          yAxisIndex: 1,
          data: timeseries.value.entity_count,
          smooth: true,
          lineStyle: { color: '#6366f1', width: 2 },
          itemStyle: { color: '#6366f1' }
        }
      ]
    })
  }
}

const downloadCSV = async () => {
  try {
    const hours = rangeToHours(timeRange.value)
    const response = await fetch(`/api/analytics/export?range=${hours}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      }
    })
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `server_stats_${timeRange.value}.csv`
    a.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('Failed to download CSV:', error)
  }
}

watch(timeRange, () => {
  loadAnalytics()
})

onMounted(() => {
  loadAnalytics()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <BarChart3 class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Analytics</h1>
      </div>
      <div class="flex items-center gap-3">
        <button
          @click="downloadCSV"
          class="flex items-center gap-2 px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg hover:bg-neutral-700 transition-colors text-sm text-neutral-300"
        >
          <Download class="w-4 h-4" />
          Export CSV
        </button>
        <div class="flex bg-neutral-800 rounded-lg border border-neutral-700 overflow-hidden">
          <button
            v-for="opt in (['24h', '7d', '30d'] as const)"
            :key="opt"
            @click="timeRange = opt"
            class="px-3 py-2 text-sm font-medium transition-colors"
            :class="timeRange === opt ? 'bg-oxide-500/15 text-oxide-400' : 'text-neutral-400 hover:text-neutral-200'"
          >
            {{ opt }}
          </button>
        </div>
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="loading" class="flex items-center justify-center py-12">
      <div class="text-neutral-500">Loading analytics...</div>
    </div>

    <template v-else-if="summary">
      <!-- Stat cards -->
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <div class="flex items-center gap-2 mb-2">
            <Users class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Peak Players</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ summary.peak_players }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last {{ timeRange }}</p>
        </div>
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <div class="flex items-center gap-2 mb-2">
            <TrendingUp class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Avg Players</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ summary.avg_players.toFixed(1) }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last {{ timeRange }}</p>
        </div>
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <div class="flex items-center gap-2 mb-2">
            <Clock class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Uptime</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ summary.uptime_percentage.toFixed(1) }}%</p>
          <p class="text-xs text-neutral-600 mt-1">Last {{ timeRange }}</p>
        </div>
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <div class="flex items-center gap-2 mb-2">
            <BarChart3 class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Unique Players</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ summary.unique_players ?? '—' }}</p>
          <p class="text-xs text-neutral-600 mt-1">Phase 2.2</p>
        </div>
      </div>

      <!-- Charts -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Player Count Over Time</h2>
          <div ref="playerChart" class="h-64"></div>
        </div>
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Server Performance</h2>
          <div ref="perfChart" class="h-64"></div>
        </div>
      </div>

      <!-- Player Retention (Phase 2.2 placeholder) -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
        <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Player Retention</h2>
        <div class="h-48 flex items-center justify-center border border-dashed border-neutral-800 rounded-lg">
          <p class="text-sm text-neutral-600">Available in Phase 2.2 — New vs returning players, session duration</p>
        </div>
      </div>
    </template>
  </div>
</template>
