<script lang="ts" setup>
import { computed } from 'vue'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import type { Affiliate, AffiliateCommission, PaginatedResponse, StatusColor } from '@/types'

interface Props {
  commissions: PaginatedResponse<AffiliateCommission>
  affiliate: Affiliate
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

function resolveStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    pending: 'warning',
    approved: 'info',
    paid: 'success',
    reversed: 'error',
  }
  return map[status] ?? 'secondary'
}

const tableHeaders = computed(() => [
  { title: 'Amount', key: 'amount', sortable: true },
  { title: 'Type', key: 'type', sortable: true },
  { title: 'Status', key: 'status', sortable: true, align: 'center' as const },
  { title: 'Date', key: 'created_at', sortable: true },
])

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}
</script>

<template>
  <div>
    <div class="text-h4 font-weight-bold mb-2">
      Commissions
    </div>
    <div class="text-body-2 text-medium-emphasis mb-6">
      Track your earned commissions
    </div>

    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="commissions.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.amount="{ item }">
          <span class="font-weight-medium">${{ parseFloat(item.amount).toFixed(2) }}</span>
          <span class="text-medium-emphasis ms-1">{{ item.currency }}</span>
        </template>

        <template #item.type="{ item }">
          <VChip
            :color="item.type === 'signup' ? 'primary' : 'info'"
            size="small"
            variant="tonal"
            class="text-capitalize"
          >
            {{ item.type }}
          </VChip>
        </template>

        <template #item.status="{ item }">
          <VChip
            :color="resolveStatusColor(item.status)"
            size="small"
            class="text-capitalize"
          >
            {{ item.status }}
          </VChip>
        </template>

        <template #item.created_at="{ item }">
          {{ formatDate(item.created_at) }}
        </template>

        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-coins" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No commissions yet.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
