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

interface Props {
  referrals: PaginatedResponse<AffiliateReferral>
  affiliate: Affiliate
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

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

function maskEmail(email: string): string {
  const [user, domain] = email.split('@')
  if (user.length <= 2) return `${user[0]}***@${domain}`
  return `${user[0]}${user[1]}***@${domain}`
}

const tableHeaders = computed(() => [
  { title: 'Referred User', key: 'referred_user', sortable: false },
  { 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">
      Referrals
    </div>
    <div class="text-body-2 text-medium-emphasis mb-6">
      Track users who signed up using your referral link
    </div>

    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="referrals.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.referred_user="{ item }">
          <span class="text-body-2">
            {{ item.referred_user ? maskEmail(item.referred_user.email) : 'N/A' }}
          </span>
        </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-users-group" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No referrals yet. Share your referral link to get started.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
