<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
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'
import Panel from '@/components/ds/data/Panel.vue'
import StatCard from '@/components/ds/data/StatCard.vue'
import Button from '@/components/ds/core/Button.vue'
import Alert from '@/components/ds/feedback/Alert.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import Tabs from '@/components/ds/navigation/Tabs.vue'

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
  }
}

function cssVar(name: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim()
}

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

  const accent = cssVar('--accent') || '#CE422B'
  const grid   = cssVar('--border-subtle') || 'rgba(255,255,255,0.06)'
  const axisLine = cssVar('--border-default') || '#404040'
  const labelColor = cssVar('--text-tertiary') || '#808080'
  const tooltipBg = cssVar('--surface-overlay') || '#1a1a1a'
  const tooltipBorder = cssVar('--border-default') || '#2a2a2a'
  const tooltipText = cssVar('--text-primary') || '#e5e5e5'
  const mono = 'JetBrains Mono, monospace'

  // 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: tooltipBg,
        borderColor: tooltipBorder,
        textStyle: { color: tooltipText, fontFamily: mono, fontSize: 11 },
        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: axisLine } },
        axisLabel: { color: labelColor, rotate: 45, fontFamily: mono, fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 1,
        axisLine: { lineStyle: { color: axisLine } },
        splitLine: { lineStyle: { color: grid } },
        axisLabel: {
          color: labelColor,
          fontFamily: mono,
          fontSize: 10,
          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: tooltipBg,
        borderColor: tooltipBorder,
        textStyle: { color: tooltipText, fontFamily: mono, fontSize: 11 }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['Day 1', 'Day 2', 'Day 3'],
        axisLine: { lineStyle: { color: axisLine } },
        axisLabel: { color: labelColor, fontFamily: mono, fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        name: 'Avg Players',
        axisLine: { lineStyle: { color: axisLine } },
        splitLine: { lineStyle: { color: grid } },
        axisLabel: { color: labelColor, fontFamily: mono, fontSize: 10 }
      },
      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: accent },
              { offset: 1, color: accent + '99' }
            ])
          },
          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: tooltipBg,
        borderColor: tooltipBorder,
        textStyle: { color: tooltipText, fontFamily: mono, fontSize: 11 },
        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: axisLine } },
        axisLabel: { color: labelColor, rotate: 45, fontFamily: mono, fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        name: 'Minutes',
        axisLine: { lineStyle: { color: axisLine } },
        splitLine: { lineStyle: { color: grid } },
        axisLabel: { color: labelColor, fontFamily: mono, fontSize: 10 }
      },
      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="wipe-analytics-view">
    <!-- Header -->
    <div class="wipe-analytics-view__header">
      <h1 class="wipe-analytics-view__title">Wipe analytics</h1>
      <div class="wipe-analytics-view__controls">
        <Button variant="secondary" size="sm" icon="download" @click="downloadCSV">
          Export CSV
        </Button>
        <Tabs
          :items="[
            { value: '6', label: 'Last 6 wipes' },
            { value: '12', label: 'Last 12 wipes' },
            { value: 'all', label: 'All time' }
          ]"
          v-model="timeRange"
          variant="pill"
        />
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="loading" class="wipe-analytics-view__loading">
      <span class="wipe-analytics-view__loading-text">Loading wipe analytics...</span>
    </div>

    <template v-else-if="metrics">
      <!-- Insight Cards -->
      <div class="wipe-analytics-view__stats">
        <StatCard
          label="Success rate"
          :value="safeFixed(metrics?.success_rate_percent, 1)"
          unit="%"
          icon="target"
          :note="`${metrics.successful_wipes}/${metrics.total_wipes} wipes`"
        />
        <StatCard
          label="Avg duration"
          :value="formatDuration(metrics.avg_duration_seconds)"
          icon="clock"
          note="Per wipe"
        />
        <StatCard
          label="Peak population"
          value="Day 1"
          icon="trending-up"
          :note="`${safeFixed(metrics?.population_curve?.day_1_avg, 1)} avg players`"
        />
        <StatCard
          label="Optimal timing"
          :value="metrics.optimal_wipe_day"
          icon="bar-chart-3"
          :note="`${metrics.optimal_wipe_hour}:00`"
        />
      </div>

      <!-- Actionable Insight Banner -->
      <Alert
        v-if="metrics.total_wipes > 3"
        tone="accent"
        title="Recommendations"
      >
        <ul class="wipe-analytics-view__recs">
          <li>Your best wipe day is <strong>{{ metrics.optimal_wipe_day }} at {{ metrics.optimal_wipe_hour }}:00</strong> 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 <strong>weekly wipes</strong> 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>
      </Alert>

      <!-- Charts -->
      <div class="wipe-analytics-view__charts">
        <Panel title="Wipe success timeline">
          <div ref="successRateChart" class="wipe-analytics-view__chart-area"></div>
        </Panel>
        <Panel title="Population curve post-wipe">
          <div ref="populationCurveChart" class="wipe-analytics-view__chart-area"></div>
        </Panel>
      </div>

      <Panel title="Wipe duration trend">
        <div ref="durationTrendChart" class="wipe-analytics-view__chart-area"></div>
      </Panel>

      <!-- No Data State -->
      <Panel v-if="metrics.total_wipes === 0">
        <EmptyState
          icon="zap"
          title="No wipe data yet"
          description="Wipe analytics will appear after your first scheduled or manual wipe."
        />
      </Panel>
    </template>
  </div>
</template>

<style scoped>
.wipe-analytics-view {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.wipe-analytics-view__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.wipe-analytics-view__title {
  font-size: var(--text-xl);
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.wipe-analytics-view__controls {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.wipe-analytics-view__loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
}

.wipe-analytics-view__loading-text {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

.wipe-analytics-view__stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

@media (min-width: 1024px) {
  .wipe-analytics-view__stats {
    grid-template-columns: repeat(4, 1fr);
  }
}

.wipe-analytics-view__charts {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

@media (min-width: 1024px) {
  .wipe-analytics-view__charts {
    grid-template-columns: 1fr 1fr;
  }
}

.wipe-analytics-view__chart-area {
  height: 256px;
}

.wipe-analytics-view__recs {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: var(--text-xs);
  color: var(--text-secondary);
  line-height: 1.5;
}

.wipe-analytics-view__recs li::before {
  content: '• ';
}
</style>
