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

interface Props {
  affiliates: PaginatedResponse<Affiliate>
  filters: {
    status: string
    search: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

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

const statusTabs: { title: string; value: string }[] = [
  { title: 'All', value: 'all' },
  { title: 'Pending', value: 'pending' },
  { title: 'Active', value: 'active' },
  { title: 'Suspended', value: 'suspended' },
]

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

const tableHeaders = computed(() => [
  { title: 'User', key: 'user', sortable: false },
  { title: 'Referral Code', key: 'referral_code', sortable: true },
  { title: 'Status', key: 'status', sortable: true, align: 'center' as const },
  { title: 'Commission', key: 'commission_rate', sortable: true },
  { title: 'Total Earned', key: 'total_earned', sortable: true, align: 'end' as const },
  { title: 'Pending', key: 'pending_balance', sortable: true, align: 'end' as const },
  { title: 'Referrals', key: 'referrals_count', sortable: true, align: 'center' as const },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
])

function applyFilters(): void {
  router.get('/affiliates', {
    status: activeTab.value,
    search: search.value || undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

watch(activeTab, applyFilters)

let searchTimeout: ReturnType<typeof setTimeout>
watch(search, () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(applyFilters, 400)
})
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Affiliates
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage affiliate partners and commissions
        </div>
      </div>
      <div class="d-flex gap-2">
        <Link href="/affiliates/commissions/queue">
          <VBtn variant="outlined" prepend-icon="tabler-coins">
            Commission Queue
          </VBtn>
        </Link>
        <Link href="/affiliates/payouts/queue">
          <VBtn variant="outlined" prepend-icon="tabler-cash-banknote">
            Payout Queue
          </VBtn>
        </Link>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="8">
            <VTabs v-model="activeTab" density="comfortable">
              <VTab
                v-for="tab in statusTabs"
                :key="tab.value"
                :value="tab.value"
              >
                {{ tab.title }}
              </VTab>
            </VTabs>
          </VCol>
          <VCol cols="12" md="4">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search affiliates..."
              variant="outlined"
              density="comfortable"
              hide-details
              clearable
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="affiliates.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.user="{ item }">
          <div v-if="item.user">
            <div class="text-body-1 font-weight-medium">
              {{ item.user.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ item.user.email }}
            </div>
          </div>
        </template>

        <template #item.referral_code="{ item }">
          <code>{{ item.referral_code }}</code>
        </template>

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

        <template #item.commission_rate="{ item }">
          {{ item.commission_type === 'percentage' ? `${item.commission_rate}%` : `$${item.commission_rate}` }}
        </template>

        <template #item.total_earned="{ item }">
          ${{ parseFloat(item.total_earned).toFixed(2) }}
        </template>

        <template #item.pending_balance="{ item }">
          ${{ parseFloat(item.pending_balance).toFixed(2) }}
        </template>

        <template #item.referrals_count="{ item }">
          {{ item.referrals_count ?? 0 }}
        </template>

        <template #item.actions="{ item }">
          <VMenu>
            <template #activator="{ props: menuProps }">
              <VBtn
                icon="tabler-dots-vertical"
                variant="text"
                size="small"
                v-bind="menuProps"
              />
            </template>
            <VList density="compact">
              <Link :href="`/affiliates/${item.id}`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-eye">
                  <VListItemTitle>View</VListItemTitle>
                </VListItem>
              </Link>
              <VListItem
                v-if="item.status === 'pending'"
                prepend-icon="tabler-check"
                @click="router.post(`/affiliates/${item.id}/approve`, {}, { preserveScroll: true })"
              >
                <VListItemTitle>Approve</VListItemTitle>
              </VListItem>
              <VListItem
                v-if="item.status === 'active'"
                prepend-icon="tabler-ban"
                @click="router.post(`/affiliates/${item.id}/suspend`, {}, { preserveScroll: true })"
              >
                <VListItemTitle>Suspend</VListItemTitle>
              </VListItem>
            </VList>
          </VMenu>
        </template>

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