<template>
  <div class="rounded-2xl border border-slate-200 bg-white shadow-sm">
    <!-- ═══ Header ═══ -->
    <div class="flex items-center justify-between px-6 py-4 border-b border-slate-100">
      <h2 class="text-lg font-bold text-slate-800">📋 {{ t('finance.transactionHistory') }}</h2>
      <!-- Filter chips -->
      <div class="flex gap-1.5">
        <button
          v-for="f in filters"
          :key="f.value"
          @click="activeFilter = f.value; currentPage = 1; fetchTransactions()"
          class="px-2.5 py-1 rounded-full text-xs font-medium transition-colors"
          :class="activeFilter === f.value
            ? 'bg-sf-accent text-white'
            : 'bg-slate-100 text-slate-500 hover:bg-slate-200'"
        >
          {{ f.label }}
        </button>
      </div>
    </div>

    <!-- ═══ Loading ═══ -->
    <div
      v-if="txLoading"
      class="flex items-center justify-center py-16"
    >
      <div class="h-10 w-10 animate-spin rounded-full border-4 border-slate-200 border-t-sf-accent" />
    </div>

    <!-- ═══ Error ═══ -->
    <div
      v-else-if="txError"
      class="flex flex-col items-center justify-center py-12 text-center px-6"
    >
      <svg class="w-12 h-12 text-red-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
      </svg>
      <p class="text-sm text-slate-500">{{ txError }}</p>
      <button
        @click="fetchTransactions"
        class="mt-3 text-sm text-sf-accent hover:underline font-medium"
      >
        {{ t('common.retry') }}
      </button>
    </div>

    <!-- ═══ Empty ═══ -->
    <div
      v-else-if="transactions.length === 0"
      class="flex flex-col items-center justify-center py-16 text-slate-400 px-6"
    >
      <svg class="w-12 h-12 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
      </svg>
      <p class="text-sm">{{ t('finance.noTransactions') }}</p>
    </div>

    <!-- ═══ Transaction List ═══ -->
    <div v-else class="divide-y divide-slate-100">
      <div
        v-for="tx in transactions"
        :key="tx.id"
        class="flex items-center justify-between px-6 py-4 hover:bg-slate-50 transition-colors"
      >
        <!-- Left: Icon + Details -->
        <div class="flex items-start gap-3 min-w-0 flex-1">
          <!-- Direction Icon -->
          <div
            class="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl"
            :class="tx.entry_type === 'CREDIT' ? 'bg-emerald-100' : 'bg-red-100'"
          >
            <span class="text-base">{{ tx.entry_type === 'CREDIT' ? '⬆' : '⬇' }}</span>
          </div>
          <!-- Details -->
          <div class="min-w-0">
            <p class="text-sm font-medium text-slate-800 truncate">
              {{ tx.description || tx.transaction_type || t('finance.transaction') }}
            </p>
            <p class="text-xs text-slate-400 mt-0.5">
              {{ formatDate(tx.created_at) }}
            </p>
            <div class="flex flex-wrap gap-1.5 mt-1.5">
              <!-- Wallet type badge -->
              <span
                class="inline-block rounded-full px-2 py-0.5 text-[10px] font-medium"
                :class="walletTypeBadge(tx.wallet_type)"
              >
                {{ walletTypeLabel(tx.wallet_type) }}
              </span>
              <!-- Status badge -->
              <span
                class="inline-block rounded-full px-2 py-0.5 text-[10px] font-medium"
                :class="statusBadge(tx.status)"
              >
                {{ statusLabel(tx.status) }}
              </span>
            </div>
          </div>
        </div>

        <!-- Right: Amount -->
        <div class="shrink-0 text-right ml-4">
          <p
            class="text-sm font-bold"
            :class="tx.entry_type === 'CREDIT' ? 'text-emerald-600' : 'text-red-600'"
          >
            {{ tx.entry_type === 'CREDIT' ? '+' : '-' }}{{ formatCredits(tx.amount) }}
          </p>
          <p class="text-[10px] text-slate-400 mt-0.5 font-mono">
            #{{ String(tx.id).slice(0, 8) }}
          </p>
        </div>
      </div>

      <!-- ═══ Pagination ═══ -->
      <div
        v-if="totalPages > 1"
        class="flex items-center justify-between px-6 py-3 bg-slate-50"
      >
        <button
          @click="prevPage"
          :disabled="currentPage <= 1"
          class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
          :class="currentPage > 1
            ? 'bg-white text-slate-600 hover:bg-slate-100 border border-slate-200'
            : 'bg-slate-50 text-slate-300 cursor-not-allowed border border-slate-100'"
        >
          &larr; {{ t('common.prev') }}
        </button>
        <span class="text-xs text-slate-400">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button
          @click="nextPage"
          :disabled="currentPage >= totalPages"
          class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
          :class="currentPage < totalPages
            ? 'bg-white text-slate-600 hover:bg-slate-100 border border-slate-200'
            : 'bg-slate-50 text-slate-300 cursor-not-allowed border border-slate-100'"
        >
          {{ t('common.next') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * TransactionHistory.vue
 *
 * Lists paginated transaction data from GET /billing/wallet/transactions.
 * Uses the financeStore and the existing i18n locale files to display
 * human-readable wallet types (EARNED, PURCHASED, SERVICE_COINS, VOUCHER)
 * and statuses (SUCCESS, PENDING, FAILED, REFUNDED, REFUND).
 *
 * Filter chips allow scoping by wallet_type. Pagination buttons at the bottom.
 */
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import api from '../../api/axios'

const { t } = useI18n()

// ── State ──
const transactions = ref<any[]>([])
const txLoading = ref(false)
const txError = ref<string | null>(null)
const currentPage = ref(1)
const totalPages = ref(1)
const totalCount = ref(0)
const activeFilter = ref<string | null>(null)
const pageSize = 20

// ── Filter definitions (use existing i18n keys from finance section) ──
const filters = computed(() => [
  { value: null, label: t('finance.all') },
  { value: 'PURCHASED', label: t('finance.purchased') },
  { value: 'EARNED', label: t('finance.earned') },
  { value: 'SERVICE_COINS', label: t('finance.bonus') },
])

// ── Formatting helpers ──

function formatCredits(value: number): string {
  if (Number.isInteger(value)) {
    return value.toLocaleString()
  }
  return value.toFixed(2)
}

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '\u2014'  // em dash
  const d = new Date(dateStr)
  return d.toLocaleDateString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// ── Wallet type badge colours + human-readable labels ──
// Uses the existing i18n finance keys for display.
function walletTypeBadge(type: string | null): string {
  switch (type) {
    case 'PURCHASED': return 'bg-blue-100 text-blue-700'
    case 'EARNED': return 'bg-emerald-100 text-emerald-700'
    case 'SERVICE_COINS': return 'bg-amber-100 text-amber-700'
    case 'VOUCHER': return 'bg-purple-100 text-purple-700'
    default: return 'bg-slate-100 text-slate-600'
  }
}

function walletTypeLabel(type: string | null): string {
  switch (type) {
    case 'PURCHASED': return t('finance.purchased')
    case 'EARNED': return t('finance.earned')
    case 'SERVICE_COINS': return t('finance.bonus')
    case 'VOUCHER': return t('finance.voucher')
    default: return type || '\u2014'
  }
}

function statusBadge(status: string | null): string {
  switch (status) {
    case 'SUCCESS': return 'bg-emerald-100 text-emerald-700'
    case 'PENDING': return 'bg-amber-100 text-amber-700'
    case 'FAILED': return 'bg-red-100 text-red-700'
    case 'REFUNDED':
    case 'REFUND': return 'bg-purple-100 text-purple-700'
    default: return 'bg-slate-100 text-slate-600'
  }
}

function statusLabel(status: string | null): string {
  switch (status) {
    case 'SUCCESS': return t('common.statusActive') || 'Success'
    case 'PENDING': return 'Pending'
    case 'FAILED': return 'Failed'
    case 'REFUNDED':
    case 'REFUND': return 'Refunded'
    default: return status || '\u2014'
  }
}

// ── API fetch ──

async function fetchTransactions() {
  txLoading.value = true
  txError.value = null
  try {
    const params: Record<string, any> = {
      page: currentPage.value,
      page_size: pageSize,
    }
    if (activeFilter.value) {
      params.wallet_type = activeFilter.value
    }

    const res = await api.get('/billing/wallet/transactions', { params })
    const data = res.data

    transactions.value = data.data || []
    totalCount.value = data.pagination?.total_count || 0
    totalPages.value = data.pagination?.total_pages || 1
  } catch (err: any) {
    const message =
      err.response?.data?.detail ||
      err.response?.data?.message ||
      'Failed to load transactions.'
    txError.value = message
    console.error('[TransactionHistory] fetch error:', err)
    transactions.value = []
  } finally {
    txLoading.value = false
  }
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchTransactions()
  }
}

function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchTransactions()
  }
}

// ── Expose for parent to trigger refresh ──
defineExpose({ fetchTransactions })

// ── Load on mount ──
onMounted(() => {
  fetchTransactions()
})
</script>
