<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import Plotly from 'plotly.js-dist-min'
import { useBacktest } from '@/composables/useBacktest'
import { compareRuns } from '@/api/client'
import type { BacktestResult, CompareResult } from '@/api/types'

const router = useRouter()
const { selectedRuns, clearSelections } = useBacktest()

const chartRef = ref<HTMLDivElement | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const compareResult = ref<CompareResult | null>(null)

const CHART_COLORS = [
  '#58a6ff', // blue
  '#a371f7', // purple
  '#39d4e8', // cyan
  '#f0883e', // orange
  '#db61a2', // pink
]

async function loadComparison() {
  if (selectedRuns.value.length < 2) {
    router.push('/')
    return
  }
  
  loading.value = true
  error.value = null
  
  try {
    compareResult.value = await compareRuns(selectedRuns.value)
    renderChart()
  } catch (e) {
    error.value = `Failed to load comparison: ${e}`
  } finally {
    loading.value = false
  }
}

function renderChart() {
  if (!chartRef.value || !compareResult.value) return
  
  const traces: Plotly.Data[] = compareResult.value.runs.map((run, idx) => {
    // Normalize equity curves to start at 100 for comparison
    const startValue = run.equity_curve[0]?.value || 1
    const normalizedValues = run.equity_curve.map(p => (p.value / startValue) * 100)
    
    return {
      x: run.equity_curve.map(p => p.timestamp),
      y: normalizedValues,
      type: 'scatter',
      mode: 'lines',
      name: `${run.strategy} (${run.params.period || ''})`,
      line: { color: CHART_COLORS[idx % CHART_COLORS.length], width: 2 },
      hovertemplate: `%{x}<br>${run.strategy}: %{y:.2f}<extra></extra>`,
    }
  })
  
  const layout: Partial<Plotly.Layout> = {
    title: {
      text: 'Normalized Equity Comparison (Base 100)',
      font: { color: '#8b949e', size: 14 },
    },
    paper_bgcolor: 'transparent',
    plot_bgcolor: 'transparent',
    margin: { l: 60, r: 20, t: 50, b: 40 },
    xaxis: {
      showgrid: true,
      gridcolor: '#30363d',
      tickfont: { color: '#8b949e', size: 10 },
      linecolor: '#30363d',
    },
    yaxis: {
      showgrid: true,
      gridcolor: '#30363d',
      tickfont: { color: '#8b949e', size: 10 },
      linecolor: '#30363d',
      title: { text: 'Normalized Value', font: { color: '#8b949e' } },
    },
    legend: {
      orientation: 'h',
      yanchor: 'bottom',
      y: 1.02,
      xanchor: 'left',
      x: 0,
      font: { color: '#8b949e' },
    },
    hovermode: 'x unified',
  }
  
  Plotly.react(chartRef.value, traces, layout, { responsive: true, displayModeBar: false })
}

function formatPercent(val: number): string {
  return (val >= 0 ? '+' : '') + val.toFixed(2) + '%'
}

function formatNumber(val: number | null): string {
  if (val === null) return '-'
  return val.toFixed(2)
}

function getBestIndex(runs: BacktestResult[], metric: keyof BacktestResult['metrics'], higher = true): number {
  let bestIdx = 0
  let bestVal = runs[0]?.metrics[metric] ?? 0
  
  for (let i = 1; i < runs.length; i++) {
    const val = runs[i]?.metrics[metric] ?? 0
    const isBetter = higher ? (val as number) > (bestVal as number) : (val as number) < (bestVal as number)
    if (isBetter) {
      bestIdx = i
      bestVal = val
    }
  }
  
  return bestIdx
}

function handleClearAndBack() {
  clearSelections()
  router.push('/')
}

onMounted(() => {
  loadComparison()
  window.addEventListener('resize', renderChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', renderChart)
  if (chartRef.value) {
    Plotly.purge(chartRef.value)
  }
})

watch(selectedRuns, () => {
  if (selectedRuns.value.length >= 2) {
    loadComparison()
  }
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold">Compare Runs</h1>
        <p class="text-text-secondary text-sm mt-1">
          Comparing {{ selectedRuns.length }} backtest runs
        </p>
      </div>
      <button @click="handleClearAndBack" class="btn btn-secondary">
        Clear & Back
      </button>
    </div>
    
    <!-- Error -->
    <div v-if="error" class="p-4 rounded-lg bg-loss/10 border border-loss/30 text-loss">
      {{ error }}
    </div>
    
    <!-- Loading -->
    <div v-if="loading" class="card flex items-center justify-center h-[400px]">
      <div class="spinner" style="width: 40px; height: 40px;"></div>
    </div>
    
    <!-- Comparison Results -->
    <template v-else-if="compareResult">
      <!-- Equity Curve Comparison -->
      <div class="card">
        <div ref="chartRef" class="h-[400px]"></div>
      </div>
      
      <!-- Metrics Comparison Table -->
      <div class="card overflow-x-auto">
        <h3 class="text-sm font-semibold text-text-secondary uppercase tracking-wide mb-4">
          Metrics Comparison
        </h3>
        <table class="min-w-full">
          <thead>
            <tr>
              <th>Metric</th>
              <th 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
              >
                <span 
                  class="inline-block w-3 h-3 rounded-full mr-2"
                  :style="{ backgroundColor: CHART_COLORS[idx] }"
                ></span>
                {{ run.strategy }}
              </th>
            </tr>
          </thead>
          <tbody>
            <!-- Total Return -->
            <tr>
              <td class="font-medium">Strategy Return</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="[
                  run.metrics.total_return >= 0 ? 'profit' : 'loss',
                  idx === getBestIndex(compareResult.runs, 'total_return') ? 'font-bold' : ''
                ]"
              >
                {{ formatPercent(run.metrics.total_return) }}
              </td>
            </tr>
            
            <!-- Benchmark Return -->
            <tr>
              <td class="font-medium">Benchmark (B&H)</td>
              <td 
                v-for="run in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="run.metrics.benchmark_return >= 0 ? 'profit' : 'loss'"
              >
                {{ formatPercent(run.metrics.benchmark_return) }}
              </td>
            </tr>
            
            <!-- Alpha -->
            <tr>
              <td class="font-medium">Alpha</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="[
                  run.metrics.alpha >= 0 ? 'profit' : 'loss',
                  idx === getBestIndex(compareResult.runs, 'alpha') ? 'font-bold' : ''
                ]"
              >
                {{ formatPercent(run.metrics.alpha) }}
              </td>
            </tr>
            
            <!-- Sharpe Ratio -->
            <tr>
              <td class="font-medium">Sharpe Ratio</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="idx === getBestIndex(compareResult.runs, 'sharpe_ratio') ? 'font-bold text-accent-blue' : ''"
              >
                {{ formatNumber(run.metrics.sharpe_ratio) }}
              </td>
            </tr>
            
            <!-- Max Drawdown -->
            <tr>
              <td class="font-medium">Max Drawdown</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center loss"
                :class="idx === getBestIndex(compareResult.runs, 'max_drawdown', false) ? 'font-bold' : ''"
              >
                {{ formatPercent(run.metrics.max_drawdown) }}
              </td>
            </tr>
            
            <!-- Win Rate -->
            <tr>
              <td class="font-medium">Win Rate</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="idx === getBestIndex(compareResult.runs, 'win_rate') ? 'font-bold text-profit' : ''"
              >
                {{ formatNumber(run.metrics.win_rate) }}%
              </td>
            </tr>
            
            <!-- Total Trades -->
            <tr>
              <td class="font-medium">Total Trades</td>
              <td 
                v-for="run in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
              >
                {{ run.metrics.total_trades }}
              </td>
            </tr>
            
            <!-- Profit Factor -->
            <tr>
              <td class="font-medium">Profit Factor</td>
              <td 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
                :class="idx === getBestIndex(compareResult.runs, 'profit_factor') ? 'font-bold text-profit' : ''"
              >
                {{ formatNumber(run.metrics.profit_factor) }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- Parameter Differences -->
      <div v-if="Object.keys(compareResult.param_diff).length > 0" class="card">
        <h3 class="text-sm font-semibold text-text-secondary uppercase tracking-wide mb-4">
          Parameter Differences
        </h3>
        <table class="min-w-full">
          <thead>
            <tr>
              <th>Parameter</th>
              <th 
                v-for="(run, idx) in compareResult.runs" 
                :key="run.run_id"
                class="text-center"
              >
                <span 
                  class="inline-block w-3 h-3 rounded-full mr-2"
                  :style="{ backgroundColor: CHART_COLORS[idx] }"
                ></span>
                Run {{ idx + 1 }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(values, key) in compareResult.param_diff" :key="key">
              <td class="font-medium font-mono">{{ key }}</td>
              <td 
                v-for="(val, idx) in values" 
                :key="idx"
                class="text-center font-mono"
              >
                {{ val ?? '-' }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>
    
    <!-- No Selection -->
    <div v-else class="card flex items-center justify-center h-[400px]">
      <div class="text-center text-text-muted">
        <p>Select at least 2 runs from the history to compare.</p>
        <button @click="router.push('/')" class="btn btn-secondary mt-4">
          Go to Dashboard
        </button>
      </div>
    </div>
  </div>
</template>
