<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { DollarSign, TrendingUp, Clock, AlertCircle, Download, RefreshCw } from 'lucide-vue-next'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { useApi } from '@/composables/useApi'
import type { StoreTransaction } from '@/types'
import { safeCurrency, safeDate } from '@/utils/formatters'

const api = useApi()

const transactions = ref<StoreTransaction[]>([])
const loading = ref(true)
const statusFilter = ref<string>('all')

const revenueChart = ref<HTMLElement | null>(null)
let revenueChartInstance: ECharts | null = null

// Summary metrics computed from transaction data
const totalRevenue = computed(() => {
  return transactions.value
    .filter(t => t.status === 'paid' || t.status === 'delivered')
    .reduce((sum, t) => sum + t.amount, 0)
})

const totalTransactions = computed(() => transactions.value.length)

const pendingDeliveries = computed(() => {
  return transactions.value.filter(t => t.status === 'paid' && !t.delivered).length
})

const refunds = computed(() => {
  return transactions.value.filter(t => t.status === 'refunded').length
})

// Filtered transactions based on status filter
const filteredTransactions = computed(() => {
  if (statusFilter.value === 'all') return transactions.value
  return transactions.value.filter(t => t.status === statusFilter.value)
})

// Format currency properly
const formatCurrency = (amount: number, currency: string = 'USD'): string => {
  const symbol = currency === 'USD' ? '$' : currency
  return safeCurrency(amount, symbol)
}

// Status badge color classes
const statusBadgeClass = (status: string): string => {
  switch (status) {
    case 'delivered': return 'bg-green-500/10 text-green-400'
    case 'paid': return 'bg-yellow-500/10 text-yellow-400'
    case 'pending': return 'bg-blue-500/10 text-blue-400'
    case 'failed': return 'bg-red-500/10 text-red-400'
    case 'refunded': return 'bg-neutral-500/10 text-neutral-400'
    default: return 'bg-neutral-700/50 text-neutral-400'
  }
}

// Format date for display
const formatDate = (dateStr: string): string => {
  return safeDate(dateStr, '—')
}

// Load transactions
const loadTransactions = async () => {
  loading.value = true
  try {
    const data = await api.get<StoreTransaction[]>('/webstore/transactions')
    transactions.value = data
    await nextTick()
    renderRevenueChart()
  } catch (error) {
    console.error('Failed to load transactions:', error)
  } finally {
    loading.value = false
  }
}

// Render revenue chart (last 30 days, grouped by day)
const renderRevenueChart = () => {
  if (!revenueChart.value || transactions.value.length === 0) return

  if (revenueChartInstance) {
    revenueChartInstance.dispose()
  }
  revenueChartInstance = echarts.init(revenueChart.value)

  // Group transactions by date and sum revenue
  const revenueByDate = new Map<string, number>()
  const last30Days = new Date()
  last30Days.setDate(last30Days.getDate() - 30)

  transactions.value
    .filter(t => (t.status === 'paid' || t.status === 'delivered') && new Date(t.created_at) >= last30Days)
    .forEach(t => {
      const dateKey = new Date(t.created_at).toLocaleDateString('en-US')
      revenueByDate.set(dateKey, (revenueByDate.get(dateKey) || 0) + t.amount)
    })

  // Generate array of last 30 days
  const dates: string[] = []
  const revenueData: number[] = []
  for (let i = 29; i >= 0; i--) {
    const d = new Date()
    d.setDate(d.getDate() - i)
    const dateKey = d.toLocaleDateString('en-US')
    dates.push(d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }))
    revenueData.push(revenueByDate.get(dateKey) || 0)
  }

  revenueChartInstance.setOption({
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#1a1a1a',
      borderColor: '#2a2a2a',
      textStyle: { color: '#e5e5e5' },
      formatter: (params: any) => {
        const value = params[0]?.data
        return `${params[0]?.axisValue ?? 'Unknown'}<br/>Revenue: ${safeCurrency(value, '$')}`
      }
    },
    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: 'Revenue ($)',
      axisLine: { lineStyle: { color: '#404040' } },
      splitLine: { lineStyle: { color: '#2a2a2a' } },
      axisLabel: { color: '#808080', formatter: (value: number) => `$${value}` }
    },
    series: [
      {
        name: 'Revenue',
        type: 'line',
        data: revenueData,
        smooth: true,
        lineStyle: { color: '#10b981', width: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(16, 185, 129, 0.3)' },
            { offset: 1, color: 'rgba(16, 185, 129, 0)' }
          ])
        },
        itemStyle: { color: '#10b981' }
      }
    ]
  })
}

// Export to CSV
const exportCSV = () => {
  if (transactions.value.length === 0) return

  let csv = 'Date,Player,Steam ID,Item ID,Amount,Currency,Status,Delivered,PayPal Order ID\n'
  transactions.value.forEach(t => {
    const date = new Date(t.created_at).toISOString()
    const playerName = (t.player_name || '').replace(/"/g, '""')
    csv += `"${date}","${playerName}","${t.steam_id}","${t.item_id || ''}",${t.amount},"${t.currency}","${t.status}",${t.delivered},"${t.paypal_order_id}"\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 = `webstore_transactions_${new Date().toISOString().split('T')[0]}.csv`
  a.click()
  window.URL.revokeObjectURL(url)
}

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

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <DollarSign class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Revenue Dashboard</h1>
      </div>
      <div class="flex items-center gap-3">
        <button
          @click="loadTransactions"
          :disabled="loading"
          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"
        >
          <RefreshCw class="w-4 h-4" :class="{ 'animate-spin': loading }" />
          Refresh
        </button>
        <button
          @click="exportCSV"
          :disabled="transactions.length === 0"
          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 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Download class="w-4 h-4" />
          Export CSV
        </button>
      </div>
    </div>

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

    <template v-else>
      <!-- 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">
            <DollarSign class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Total Revenue</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ formatCurrency(totalRevenue) }}</p>
          <p class="text-xs text-neutral-600 mt-1">Last 100 transactions</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">Total Transactions</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ totalTransactions }}</p>
          <p class="text-xs text-neutral-600 mt-1">All time</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">Pending Deliveries</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ pendingDeliveries }}</p>
          <p class="text-xs text-neutral-600 mt-1">Paid, not delivered</p>
        </div>

        <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
          <div class="flex items-center gap-2 mb-2">
            <AlertCircle class="w-4 h-4 text-neutral-500" />
            <p class="text-sm text-neutral-400">Refunds</p>
          </div>
          <p class="text-2xl font-bold text-neutral-100">{{ refunds }}</p>
          <p class="text-xs text-neutral-600 mt-1">Total refunded</p>
        </div>
      </div>

      <!-- Revenue 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">Revenue Over Time (Last 30 Days)</h2>
        <div ref="revenueChart" class="h-64"></div>
      </div>

      <!-- Transaction Table -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
        <div class="px-4 py-3 border-b border-neutral-800 flex items-center justify-between">
          <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">Transaction History</h2>
          <div class="flex items-center gap-2">
            <label class="text-xs text-neutral-500">Filter:</label>
            <select
              v-model="statusFilter"
              class="px-2 py-1 text-xs bg-neutral-800 border border-neutral-700 rounded text-neutral-300 focus:outline-none focus:border-oxide-500"
            >
              <option value="all">All</option>
              <option value="delivered">Delivered</option>
              <option value="paid">Paid</option>
              <option value="pending">Pending</option>
              <option value="failed">Failed</option>
              <option value="refunded">Refunded</option>
            </select>
          </div>
        </div>

        <table class="w-full">
          <thead>
            <tr class="border-b border-neutral-800 text-left">
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Date</th>
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Player</th>
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Item</th>
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Amount</th>
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Status</th>
              <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Delivered</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-neutral-800">
            <tr v-if="filteredTransactions.length === 0">
              <td colspan="6" class="px-4 py-12 text-center text-neutral-500 text-sm">
                <template v-if="statusFilter !== 'all'">No {{ statusFilter }} transactions found.</template>
                <template v-else>No transactions yet. Sales will appear here.</template>
              </td>
            </tr>
            <tr
              v-for="txn in filteredTransactions"
              :key="txn.id"
              class="hover:bg-neutral-800/50 transition-colors"
            >
              <td class="px-4 py-3">
                <p class="text-sm text-neutral-300">{{ formatDate(txn.created_at) }}</p>
              </td>
              <td class="px-4 py-3">
                <p class="text-sm font-medium text-neutral-100">{{ txn.player_name || 'Unknown' }}</p>
                <p class="text-xs text-neutral-500 font-mono">{{ txn.steam_id }}</p>
              </td>
              <td class="px-4 py-3">
                <p class="text-sm text-neutral-300">{{ txn.item_id || '—' }}</p>
              </td>
              <td class="px-4 py-3">
                <p class="text-sm font-medium text-neutral-200">{{ formatCurrency(txn.amount, txn.currency) }}</p>
              </td>
              <td class="px-4 py-3">
                <span
                  class="text-xs font-medium px-2 py-0.5 rounded-full uppercase"
                  :class="statusBadgeClass(txn.status)"
                >
                  {{ txn.status }}
                </span>
              </td>
              <td class="px-4 py-3">
                <span
                  class="text-xs font-medium px-2 py-0.5 rounded-full"
                  :class="txn.delivered ? 'bg-green-500/10 text-green-400' : 'bg-neutral-700/50 text-neutral-400'"
                >
                  {{ txn.delivered ? 'Yes' : 'No' }}
                </span>
                <p v-if="txn.delivered_at" class="text-xs text-neutral-600 mt-1">
                  {{ formatDate(txn.delivered_at) }}
                </p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>
  </div>
</template>
