<script lang="ts" setup>
import { Link, router } from '@inertiajs/vue3'
import { ref, watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { formatPrice, resolveTransactionStatusColor } from '@/utils/resolvers'
import type { PaginatedResponse, StatusColor } from '@/types'

interface TransactionUser {
  id: number
  name: string
  email: string
}

interface TransactionInvoice {
  id: number
  number: string
}

interface TransactionItem {
  id: number
  user_id: number
  invoice_id: number | null
  gateway: string
  gateway_transaction_id: string | null
  amount: string
  currency: string
  status: string
  payment_method: string | null
  description: string | null
  created_at: string
  user: TransactionUser | null
  invoice: TransactionInvoice | null
}

interface Filters {
  search: string
  status: string
  gateway: string
}

interface Props {
  transactions: PaginatedResponse<TransactionItem>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const status = ref<string>(props.filters.status)
const gateway = ref<string>(props.filters.gateway)

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Succeeded', value: 'succeeded' },
  { title: 'Failed', value: 'failed' },
  { title: 'Pending', value: 'pending' },
  { title: 'Refunded', value: 'refunded' },
  { title: 'Canceled', value: 'canceled' },
]

const gatewayOptions = [
  { title: 'All Gateways', value: '' },
  { title: 'Stripe', value: 'stripe' },
  { title: 'PayPal', value: 'paypal' },
]

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function applyFilters(): void {
  router.get('/transactions', {
    search: search.value || undefined,
    status: status.value || undefined,
    gateway: gateway.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

watch(search, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(applyFilters, 300)
})

watch([status, gateway], () => {
  applyFilters()
})

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}

function formatAmount(amount: string, status: string): string {
  const num = parseFloat(amount)
  const prefix = status === 'refunded' ? '-' : ''
  return `${prefix}${formatPrice(Math.abs(num).toFixed(2))}`
}

function resolveGatewayColor(gw: string): StatusColor {
  const map: Record<string, StatusColor> = {
    stripe: 'info',
    paypal: 'warning',
  }
  return map[gw] ?? 'secondary'
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Transactions
        </div>
        <div class="text-body-2 text-medium-emphasis">
          View all payment transactions
        </div>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="6">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by transaction ID, customer name, or email..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VSelect
              v-model="gateway"
              :items="gatewayOptions"
              density="compact"
              hide-details
              label="Gateway"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Transactions Table -->
    <VCard>
      <VCardText v-if="transactions.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-cash-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No transactions found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Transaction ID</th>
            <th>Customer</th>
            <th>Invoice</th>
            <th class="text-end">
              Amount
            </th>
            <th>Status</th>
            <th>Gateway</th>
            <th>Date</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="tx in transactions.data" :key="tx.id">
            <td class="text-body-2 font-weight-medium" style="max-width: 200px;">
              <span class="d-inline-block text-truncate" style="max-width: 180px;" :title="tx.gateway_transaction_id ?? ''">
                {{ tx.gateway_transaction_id ?? '---' }}
              </span>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ tx.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ tx.user?.email ?? '' }}</span>
              </div>
            </td>
            <td class="text-body-2">
              <Link v-if="tx.invoice" :href="`/invoices/${tx.invoice.id}`" class="text-primary text-decoration-none">
                {{ tx.invoice.number }}
              </Link>
              <span v-else class="text-medium-emphasis">---</span>
            </td>
            <td class="text-end text-body-2 font-weight-medium">
              {{ formatAmount(tx.amount, tx.status) }}
            </td>
            <td>
              <VChip
                :color="resolveTransactionStatusColor(tx.status)"
                size="small"
                class="text-capitalize"
              >
                {{ tx.status }}
              </VChip>
            </td>
            <td>
              <VChip
                :color="resolveGatewayColor(tx.gateway)"
                size="small"
                variant="outlined"
                class="text-capitalize"
              >
                {{ tx.gateway }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ formatDate(tx.created_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/transactions/${tx.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="transactions.last_page > 1" class="d-flex align-center justify-center pt-2">
        <VPagination
          :model-value="transactions.data.length > 0 ? Math.ceil((transactions.from ?? 1) / 25) : 1"
          :length="transactions.last_page"
          :total-visible="7"
          @update:model-value="(page: number) => router.get('/transactions', { ...props.filters, page }, { preserveState: true, preserveScroll: true })"
        />
      </VCardText>

      <VCardText v-if="transactions.total > 0" class="text-center text-caption text-medium-emphasis">
        Showing {{ transactions.from }} to {{ transactions.to }} of {{ transactions.total }} transactions
      </VCardText>
    </VCard>
  </div>
</template>
