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

const api = useApi()

const timeRange = ref<'6' | '12' | 'all'>('12')
const loading = ref(true)
const metrics = ref<WipePerformanceMetrics | null>(null)

const successRateChart = ref<HTMLElement | null>(null)
const populationCurveChart = ref<HTMLElement | null>(null)
const durationTrendChart = ref<HTMLElement | null>(null)

let successRateChartInstance: ECharts | null = null
let populationCurveChartInstance: ECharts | null = null
let durationTrendChartInstance: ECharts | null = null

const rangeToParam = (range: string): string => {
  if (range === 'all') return 'all'
  return `${parseInt(range) * 30}d` // 6 wipes = ~180d, 12 wipes = ~360d (monthly wipes)
}

const loadAnalytics = async () => {
  loading.value = true
  try {
    const range = rangeToParam(timeRange.value)
    const response = await api.get<WipePerformanceMetrics>(`/analytics/wipes/performance?range=${range}`)
    metrics.value = response

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

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

  // Success Rate Timeline
  if (successRateChart.value) {
    if (successRateChartInstance) {
      successRateChartInstance.dispose()
    }
    successRateChartInstance = echarts.init(successRateChart.value)

    const successData = metrics.value.wipes.map(w => w.success ? 1 : 0)
    const dates = metrics.value.wipes.map(w => new Date(w.date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric'
    }))

    successRateChartInstance.setOption({
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#1a1a1a',
        borderColor: '#2a2a2a',
        textStyle: { color: '#e5e5e5' },
        formatter: (params: any) => {
          const status = params[0].data === 1 ? 'Success' : 'Failed'
          const color = params[0].data === 1 ? '#10b981' : '#ef4444'
          return `<span style="color:${color}">●</span> ${params[0].axisValue}: ${status}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080', rotate: 45 }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 1,
        axisLine: { lineStyle: { color: '#404040' } },
        splitLine: { lineStyle: { color: '#2a2a2a' } },
        axisLabel: {
          color: '#808080',
          formatter: (value: number) => value === 1 ? 'Success' : 'Failed'
        }
      },
      series: [
        {
          name: 'Wipe Status',
          type: 'scatter',
          data: successData,
          symbolSize: 10,
          itemStyle: {
            color: (params: any) => params.data === 1 ? '#10b981' : '#ef4444'
          }
        }
      ]
    })
  }

  // Population Curve (Day 1 vs Day 2 vs Day 3)
  if (populationCurveChart.value) {
    if (populationCurveChartInstance) {
      populationCurveChartInstance.dispose()
    }
    populationCurveChartInstance = echarts.init(populationCurveChart.value)

    const { population_curve } = metrics.value

    populationCurveChartInstance.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: ['Day 1', 'Day 2', 'Day 3'],
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080' }
      },
      yAxis: {
        type: 'value',
        name: 'Avg Players',
        axisLine: { lineStyle: { color: '#404040' } },
        splitLine: { lineStyle: { color: '#2a2a2a' } },
        axisLabel: { color: '#808080' }
      },
      series: [
        {
          name: 'Average Players',
          type: 'bar',
          data: [
            population_curve.day_1_avg,
            population_curve.day_2_avg,
            population_curve.day_3_avg
          ],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#CE422B' },
              { offset: 1, color: '#8B2E1F' }
            ])
          },
          barWidth: '50%'
        }
      ]
    })
  }

  // Wipe Duration Trend
  if (durationTrendChart.value) {
    if (durationTrendChartInstance) {
      durationTrendChartInstance.dispose()
    }
    durationTrendChartInstance = echarts.init(durationTrendChart.value)

    const durations = metrics.value.wipes.map(w => safeFixed(w.duration_seconds / 60, 1))
    const dates = metrics.value.wipes.map(w => new Date(w.date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric'
    }))

    durationTrendChartInstance.setOption({
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#1a1a1a',
        borderColor: '#2a2a2a',
        textStyle: { color: '#e5e5e5' },
        formatter: (params: any) => {
          return `${params[0].axisValue}<br/>Duration: ${params[0].data} minutes`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080', rotate: 45 }
      },
      yAxis: {
        type: 'value',
        name: 'Minutes',
        axisLine: { lineStyle: { color: '#404040' } },
        splitLine: { lineStyle: { color: '#2a2a2a' } },
        axisLabel: { color: '#808080' }
      },
      series: [
        {
          name: 'Duration',
          type: 'line',
          data: durations,
          smooth: true,
          lineStyle: { color: '#6366f1', width: 2 },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(99, 102, 241, 0.3)' },
              { offset: 1, color: 'rgba(99, 102, 241, 0)' }
            ])
          },
          itemStyle: { color: '#6366f1' }
        }
      ]
    })
  }
}

const formatDuration = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${minutes}m ${secs}s`
}

const downloadCSV = async () => {
  if (!metrics.value) return

  let csv = 'Date,Duration (seconds),Peak Population,Hours to Peak,Success\n'
  metrics.value.wipes.forEach(wipe => {
    csv += `${new Date(wipe.date).toISOString()},${wipe.duration_seconds},${wipe.peak_population},${safeFixed(wipe.hours_to_peak, 2)},${wipe.success}\n`
  })

  const blob = new Blob([csv], { type: 'text/csv' })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `wipe_analytics_${timeRange.value}.csv`
  a.click()
  window.URL.revokeObjectURL(url)
}

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">
        <Zap class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Wipe 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 (['6', '12', 'all'] 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 === 'all' ? 'All Time' : `Last ${opt} Wipes` }}
          </button>
        </div>
      </div>
    </div>

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

    <template v-else-if="metrics">
      <!-- Insight 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">
            <Target class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Success Rate</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ safeFixed(metrics?.success_rate_percent, 1) }}%</p>
          <p class="text-xs text-neutral-600 mt-1">{{ metrics.successful_wipes }}/{{ metrics.total_wipes }} wipes</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">Avg Duration</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ formatDuration(metrics.avg_duration_seconds) }}</p>
          <p class="text-xs text-neutral-600 mt-1">Per wipe</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">Peak Population</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">Day 1</p>
          <p class="text-xs text-neutral-600 mt-1">{{ safeFixed(metrics?.population_curve?.day_1_avg, 1) }} avg players</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">Optimal Timing</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ metrics.optimal_wipe_day }}</p>
          <p class="text-xs text-neutral-600 mt-1">{{ metrics.optimal_wipe_hour }}:00</p>
        </div>
      </div>

      <!-- Actionable Insight Banner -->
      <div v-if="metrics.total_wipes > 3" class="bg-oxide-500/10 border border-oxide-500/30 rounded-lg p-4">
        <div class="flex items-start gap-3">
          <Target class="w-5 h-5 text-oxide-400 mt-0.5" />
          <div>
            <p class="text-sm font-medium text-neutral-100 mb-1">Recommendations</p>
            <ul class="text-sm text-neutral-300 space-y-1">
              <li>• Your best wipe day is <span class="font-semibold text-oxide-400">{{ metrics.optimal_wipe_day }} at {{ metrics.optimal_wipe_hour }}:00</span> based on post-wipe population peaks.</li>
              <li v-if="metrics.population_curve.day_1_avg > metrics.population_curve.day_2_avg * 1.2">
                • Players peak on Day 1 ({{ safeFixed(metrics?.population_curve?.day_1_avg, 0) }} avg). Consider <span class="font-semibold text-oxide-400">weekly wipes</span> to maintain engagement.
              </li>
              <li v-if="metrics.avg_duration_seconds > 600">
                • Average wipe duration is {{ formatDuration(metrics.avg_duration_seconds) }}. Review pre-wipe commands for optimization opportunities.
              </li>
              <li v-if="metrics.success_rate_percent < 95 && metrics.failed_wipes > 0">
                • {{ metrics.failed_wipes }} wipe(s) failed. Enable rollback protection in wipe profiles.
              </li>
            </ul>
          </div>
        </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">Wipe Success Timeline</h2>
          <div ref="successRateChart" 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">Population Curve Post-Wipe</h2>
          <div ref="populationCurveChart" class="h-64"></div>
        </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">Wipe Duration Trend</h2>
        <div ref="durationTrendChart" class="h-64"></div>
      </div>

      <!-- No Data State -->
      <div v-if="metrics.total_wipes === 0" class="bg-neutral-900 border border-neutral-800 rounded-lg p-8">
        <div class="text-center">
          <Zap class="w-12 h-12 text-neutral-700 mx-auto mb-3" />
          <p class="text-neutral-400 mb-1">No wipe data yet</p>
          <p class="text-sm text-neutral-600">Wipe analytics will appear after your first scheduled or manual wipe.</p>
        </div>
      </div>
    </template>
  </div>
</template>
