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

const api = useApi()
const authStore = useAuthStore()

interface WipeRetentionMetric {
  wipe_id: string
  wipe_date: string
  total_players_before_wipe: number
  returned_24h: number
  returned_48h: number
  returned_72h: number
  retention_24h_percent: number
  retention_48h_percent: number
  retention_72h_percent: number
}

interface SessionSummary {
  unique_players: number
  total_sessions: number
  avg_session_duration_minutes: number
  new_players: number
  returning_players: number
  new_vs_returning_ratio: number
}

interface RetentionResponse {
  wipe_metrics: WipeRetentionMetric[]
  summary: SessionSummary
}

const wipeCount = ref<number>(6)
const loading = ref(true)
const retentionData = ref<RetentionResponse | null>(null)

const retentionChart = ref<HTMLElement | null>(null)
let retentionChartInstance: ECharts | null = null

const loadRetentionData = async () => {
  loading.value = true
  try {
    const response = await api.get<RetentionResponse>(
      `/analytics/retention?wipe_count=${wipeCount.value}`
    )
    retentionData.value = response

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

const renderCharts = () => {
  if (!retentionData.value || !retentionData.value.wipe_metrics.length) return

  // Retention curve chart (24h/48h/72h over multiple wipes)
  if (retentionChart.value) {
    if (retentionChartInstance) {
      retentionChartInstance.dispose()
    }
    retentionChartInstance = echarts.init(retentionChart.value)

    const wipeLabels = retentionData.value.wipe_metrics.map((w) =>
      new Date(w.wipe_date).toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric'
      })
    )

    const retention24h = retentionData.value.wipe_metrics.map((w) => w.retention_24h_percent)
    const retention48h = retentionData.value.wipe_metrics.map((w) => w.retention_48h_percent)
    const retention72h = retentionData.value.wipe_metrics.map((w) => w.retention_72h_percent)

    retentionChartInstance.setOption({
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#1a1a1a',
        borderColor: '#2a2a2a',
        textStyle: { color: '#e5e5e5' },
        formatter: (params: any) => {
          let tooltip = `<strong>${params[0].axisValue}</strong><br/>`
          params.forEach((param: any) => {
            tooltip += `${param.marker} ${param.seriesName}: ${safeFixed(param.value, 1)}%<br/>`
          })
          return tooltip
        }
      },
      legend: {
        data: ['24h Return', '48h Return', '72h Return'],
        textStyle: { color: '#a3a3a3' },
        top: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: wipeLabels,
        axisLine: { lineStyle: { color: '#404040' } },
        axisLabel: { color: '#808080', rotate: 45 }
      },
      yAxis: {
        type: 'value',
        name: 'Retention %',
        axisLine: { lineStyle: { color: '#404040' } },
        splitLine: { lineStyle: { color: '#2a2a2a' } },
        axisLabel: {
          color: '#808080',
          formatter: (value: number) => `${value}%`
        },
        max: 100
      },
      series: [
        {
          name: '24h Return',
          type: 'line',
          data: retention24h,
          smooth: true,
          lineStyle: { color: '#CE422B', width: 3 },
          itemStyle: { color: '#CE422B' },
          symbolSize: 8
        },
        {
          name: '48h Return',
          type: 'line',
          data: retention48h,
          smooth: true,
          lineStyle: { color: '#f59e0b', width: 3 },
          itemStyle: { color: '#f59e0b' },
          symbolSize: 8
        },
        {
          name: '72h Return',
          type: 'line',
          data: retention72h,
          smooth: true,
          lineStyle: { color: '#10b981', width: 3 },
          itemStyle: { color: '#10b981' },
          symbolSize: 8
        }
      ]
    })
  }
}

const downloadCSV = async () => {
  try {
    const response = await fetch(`/api/analytics/retention/export?wipe_count=${wipeCount.value}`, {
      headers: {
        Authorization: `Bearer ${authStore.accessToken}`
      }
    })
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `retention_metrics_${wipeCount.value}_wipes.csv`
    a.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('Failed to download CSV:', error)
  }
}

watch(wipeCount, () => {
  loadRetentionData()
})

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

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <Users class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Player Retention</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 items-center gap-2 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-2">
          <label class="text-sm text-neutral-400">Wipes:</label>
          <select
            v-model.number="wipeCount"
            class="bg-transparent text-neutral-100 text-sm focus:outline-none"
          >
            <option :value="3">Last 3</option>
            <option :value="6">Last 6</option>
            <option :value="10">Last 10</option>
            <option :value="20">Last 20</option>
          </select>
        </div>
      </div>
    </div>

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

    <template v-else-if="retentionData && retentionData.wipe_metrics.length > 0">
      <!-- Summary 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">Unique Players</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ retentionData.summary.unique_players }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last 30 days</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 Session</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">
            {{ safeFixed(retentionData?.summary?.avg_session_duration_minutes, 0) }}m
          </p>
          <p class="text-xs text-neutral-600 mt-1">Duration</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">New Players</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ retentionData.summary.new_players }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last 30 days</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">Returning</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ retentionData.summary.returning_players }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last 30 days</p>
        </div>
      </div>

      <!-- Retention curve chart -->
      <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">
          Retention Curve (Post-Wipe Return Rates)
        </h2>
        <div ref="retentionChart" class="h-96"></div>
        <div class="mt-4 text-xs text-neutral-500">
          <p>
            <strong>How to read:</strong> Percentage of players who played in the 7 days before a wipe and
            returned within 24h/48h/72h after the wipe.
          </p>
        </div>
      </div>

      <!-- Wipe details table -->
      <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 Details
        </h2>
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-neutral-800">
                <th class="text-left py-2 px-3 text-neutral-400 font-medium">Wipe Date</th>
                <th class="text-right py-2 px-3 text-neutral-400 font-medium">Pre-Wipe Players</th>
                <th class="text-right py-2 px-3 text-neutral-400 font-medium">24h Return</th>
                <th class="text-right py-2 px-3 text-neutral-400 font-medium">48h Return</th>
                <th class="text-right py-2 px-3 text-neutral-400 font-medium">72h Return</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="wipe in retentionData.wipe_metrics"
                :key="wipe.wipe_id"
                class="border-b border-neutral-800 hover:bg-neutral-800/50 transition-colors"
              >
                <td class="py-3 px-3 text-neutral-300">
                  {{ new Date(wipe.wipe_date).toLocaleString('en-US', {
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                  }) }}
                </td>
                <td class="py-3 px-3 text-right text-neutral-300">
                  {{ wipe.total_players_before_wipe }}
                </td>
                <td class="py-3 px-3 text-right">
                  <span class="text-neutral-100 font-medium">{{ wipe.returned_24h }}</span>
                  <span class="text-neutral-500 text-xs ml-1">({{ safeFixed(wipe.retention_24h_percent, 1) }}%)</span>
                </td>
                <td class="py-3 px-3 text-right">
                  <span class="text-neutral-100 font-medium">{{ wipe.returned_48h }}</span>
                  <span class="text-neutral-500 text-xs ml-1">({{ safeFixed(wipe.retention_48h_percent, 1) }}%)</span>
                </td>
                <td class="py-3 px-3 text-right">
                  <span class="text-neutral-100 font-medium">{{ wipe.returned_72h }}</span>
                  <span class="text-neutral-500 text-xs ml-1">({{ safeFixed(wipe.retention_72h_percent, 1) }}%)</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </template>

    <!-- Empty state -->
    <div
      v-else
      class="bg-neutral-900 border border-neutral-800 rounded-lg p-12 text-center"
    >
      <Users class="w-12 h-12 text-neutral-700 mx-auto mb-4" />
      <p class="text-neutral-500 mb-2">No retention data available</p>
      <p class="text-sm text-neutral-600">
        Player retention metrics will appear here after wipes are tracked and players join/leave.
      </p>
    </div>
  </div>
</template>
