<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import { resolveTransactionStatusColor } from '@/utils/resolvers'
import type { Transaction, PaginatedResponse } from '@/types'

interface Props {
  transactions: PaginatedResponse<Transaction>
}

defineOptions({ layout: AccountLayout })

defineProps<Props>()
</script>

<template>
  <div>
    <div class="mb-4">
      <Link href="/billing" class="text-primary text-body-2 text-decoration-none">&larr; Back to Billing</Link>
    </div>

    <div class="text-h4 font-weight-bold mb-6">Transactions</div>

    <VCard>
      <VCardText v-if="!transactions.data || transactions.data.length === 0" class="text-center py-6">
        <div class="text-medium-emphasis">No transactions found.</div>
      </VCardText>

      <template v-else>
        <VTable>
          <thead>
            <tr>
              <th>Date</th>
              <th>Gateway</th>
              <th>Method</th>
              <th>Status</th>
              <th>Description</th>
              <th class="text-end">Amount</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="tx in transactions.data" :key="tx.id">
              <td>{{ new Date(tx.created_at).toLocaleDateString() }}</td>
              <td class="text-capitalize">{{ tx.gateway }}</td>
              <td class="text-capitalize">{{ tx.payment_method }}</td>
              <td>
                <VChip
                  :color="resolveTransactionStatusColor(tx.status)"
                  size="small"
                  class="text-capitalize"
                >
                  {{ tx.status }}
                </VChip>
              </td>
              <td>{{ tx.description }}</td>
              <td class="text-end">${{ parseFloat(tx.amount).toFixed(2) }}</td>
            </tr>
          </tbody>
        </VTable>

        <!-- Pagination -->
        <div v-if="transactions.links && transactions.last_page > 1" class="d-flex align-center justify-space-between pa-4">
          <div class="text-body-2 text-medium-emphasis">
            Showing {{ transactions.from }} to {{ transactions.to }} of {{ transactions.total }}
          </div>
          <div class="d-flex ga-1">
            <Link
              v-for="link in transactions.links"
              :key="link.label"
              :href="link.url || '#'"
              class="text-decoration-none"
            >
              <VBtn
                size="small"
                :color="link.active ? 'primary' : undefined"
                :variant="link.active ? 'flat' : 'text'"
                :disabled="!link.url"
                v-html="link.label"
              />
            </Link>
          </div>
        </div>
      </template>
    </VCard>
  </div>
</template>
