<script setup lang="ts">
import { ref, computed } from 'vue'
import type { TradeRecord } from '@/api/types'

const props = defineProps<{
  trades: TradeRecord[]
}>()

type SortKey = 'entry_time' | 'pnl' | 'return_pct' | 'size'
const sortKey = ref<SortKey>('entry_time')
const sortDesc = ref(true)

const sortedTrades = computed(() => {
  return [...props.trades].sort((a, b) => {
    let aVal: number | string = 0
    let bVal: number | string = 0
    
    switch (sortKey.value) {
      case 'entry_time':
        aVal = a.entry_time
        bVal = b.entry_time
        break
      case 'pnl':
        aVal = a.pnl ?? 0
        bVal = b.pnl ?? 0
        break
      case 'return_pct':
        aVal = a.return_pct ?? 0
        bVal = b.return_pct ?? 0
        break
      case 'size':
        aVal = a.size
        bVal = b.size
        break
    }
    
    if (aVal < bVal) return sortDesc.value ? 1 : -1
    if (aVal > bVal) return sortDesc.value ? -1 : 1
    return 0
  })
})

function toggleSort(key: SortKey) {
  if (sortKey.value === key) {
    sortDesc.value = !sortDesc.value
  } else {
    sortKey.value = key
    sortDesc.value = true
  }
}

function formatDate(iso: string): string {
  if (!iso) return '-'
  const d = new Date(iso)
  return d.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function formatPrice(val: number | null): string {
  if (val === null) return '-'
  return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function formatPnL(val: number | null): string {
  if (val === null) return '-'
  const sign = val >= 0 ? '+' : ''
  return sign + val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function formatReturn(val: number | null): string {
  if (val === null) return '-'
  return (val >= 0 ? '+' : '') + val.toFixed(2) + '%'
}
</script>

<template>
  <div class="card overflow-hidden">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-sm font-semibold text-text-secondary uppercase tracking-wide">
        Trade Log
      </h3>
      <span class="text-xs text-text-muted">{{ trades.length }} trades</span>
    </div>
    
    <div class="overflow-x-auto max-h-[400px] overflow-y-auto">
      <table class="min-w-full">
        <thead class="sticky top-0 bg-bg-card">
          <tr>
            <th 
              @click="toggleSort('entry_time')" 
              class="cursor-pointer hover:text-text-primary"
            >
              Entry Time
              <span v-if="sortKey === 'entry_time'">{{ sortDesc ? ' v' : ' ^' }}</span>
            </th>
            <th>Exit Time</th>
            <th>Direction</th>
            <th>Entry</th>
            <th>Exit</th>
            <th 
              @click="toggleSort('size')" 
              class="cursor-pointer hover:text-text-primary"
            >
              Size
              <span v-if="sortKey === 'size'">{{ sortDesc ? ' v' : ' ^' }}</span>
            </th>
            <th 
              @click="toggleSort('pnl')" 
              class="cursor-pointer hover:text-text-primary"
            >
              PnL
              <span v-if="sortKey === 'pnl'">{{ sortDesc ? ' v' : ' ^' }}</span>
            </th>
            <th 
              @click="toggleSort('return_pct')" 
              class="cursor-pointer hover:text-text-primary"
            >
              Return
              <span v-if="sortKey === 'return_pct'">{{ sortDesc ? ' v' : ' ^' }}</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(trade, idx) in sortedTrades" :key="idx">
            <td class="text-text-secondary">{{ formatDate(trade.entry_time) }}</td>
            <td class="text-text-secondary">{{ formatDate(trade.exit_time || '') }}</td>
            <td>
              <span 
                class="px-2 py-0.5 rounded text-xs font-medium"
                :class="trade.direction === 'Long' ? 'bg-profit/20 text-profit' : 'bg-loss/20 text-loss'"
              >
                {{ trade.direction }}
              </span>
            </td>
            <td>${{ formatPrice(trade.entry_price) }}</td>
            <td>${{ formatPrice(trade.exit_price) }}</td>
            <td>{{ trade.size.toFixed(4) }}</td>
            <td :class="(trade.pnl ?? 0) >= 0 ? 'profit' : 'loss'">
              ${{ formatPnL(trade.pnl) }}
            </td>
            <td :class="(trade.return_pct ?? 0) >= 0 ? 'profit' : 'loss'">
              {{ formatReturn(trade.return_pct) }}
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-if="trades.length === 0" class="p-8 text-center text-text-muted">
        No trades executed.
      </div>
    </div>
  </div>
</template>
