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

interface Props {
  affiliate: Affiliate
  referrals: PaginatedResponse<AffiliateReferral>
  commissions: PaginatedResponse<AffiliateCommission>
  payouts: PaginatedResponse<AffiliatePayout>
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const activeTab = ref<string>('referrals')

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

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

function formatMethod(method: string): string {
  const map: Record<string, string> = {
    credit: 'Account Credit',
    paypal: 'PayPal',
    bank_transfer: 'Bank Transfer',
  }
  return map[method] ?? method
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Affiliate: {{ affiliate.user?.name }}
        </div>
        <div class="text-body-2 text-medium-emphasis">
          {{ affiliate.user?.email }} &mdash; Code: <code>{{ affiliate.referral_code }}</code>
        </div>
      </div>
      <div class="d-flex gap-2">
        <VBtn
          v-if="affiliate.status === 'pending'"
          color="success"
          prepend-icon="tabler-check"
          @click="router.post(`/affiliates/${affiliate.id}/approve`, {}, { preserveScroll: true })"
        >
          Approve
        </VBtn>
        <VBtn
          v-if="affiliate.status === 'active'"
          color="error"
          variant="outlined"
          prepend-icon="tabler-ban"
          @click="router.post(`/affiliates/${affiliate.id}/suspend`, {}, { preserveScroll: true })"
        >
          Suspend
        </VBtn>
      </div>
    </div>

    <!-- Summary Cards -->
    <VRow class="mb-6">
      <VCol cols="12" sm="6" md="3">
        <VCard>
          <VCardText class="text-center">
            <div class="text-body-2 text-medium-emphasis mb-1">
              Status
            </div>
            <VChip
              :color="resolveStatusColor(affiliate.status)"
              size="small"
              class="text-capitalize"
            >
              {{ affiliate.status }}
            </VChip>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" sm="6" md="3">
        <VCard>
          <VCardText class="text-center">
            <div class="text-body-2 text-medium-emphasis mb-1">
              Total Earned
            </div>
            <div class="text-h5 font-weight-bold">
              ${{ parseFloat(affiliate.total_earned).toFixed(2) }}
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" sm="6" md="3">
        <VCard>
          <VCardText class="text-center">
            <div class="text-body-2 text-medium-emphasis mb-1">
              Pending Balance
            </div>
            <div class="text-h5 font-weight-bold text-warning">
              ${{ parseFloat(affiliate.pending_balance).toFixed(2) }}
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" sm="6" md="3">
        <VCard>
          <VCardText class="text-center">
            <div class="text-body-2 text-medium-emphasis mb-1">
              Commission
            </div>
            <div class="text-h5 font-weight-bold">
              {{ affiliate.commission_type === 'percentage' ? `${affiliate.commission_rate}%` : `$${affiliate.commission_rate}` }}
            </div>
            <div class="text-caption text-medium-emphasis">
              {{ affiliate.recurring_commissions ? 'Recurring' : 'One-time' }}
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Tabs -->
    <VCard>
      <VTabs v-model="activeTab" class="px-4 pt-2">
        <VTab value="referrals">
          Referrals ({{ affiliate.referrals_count ?? 0 }})
        </VTab>
        <VTab value="commissions">
          Commissions ({{ affiliate.commissions_count ?? 0 }})
        </VTab>
        <VTab value="payouts">
          Payouts ({{ affiliate.payouts_count ?? 0 }})
        </VTab>
      </VTabs>

      <VCardText>
        <!-- Referrals Tab -->
        <VDataTable
          v-if="activeTab === 'referrals'"
          :headers="[
            { title: 'User', key: 'referred_user', sortable: false },
            { title: 'IP', key: 'signup_ip', sortable: false },
            { title: 'Status', key: 'status', sortable: true, align: 'center' },
            { title: 'Date', key: 'created_at', sortable: true },
          ]"
          :items="referrals.data"
          :items-per-page="10"
          hover
          class="text-no-wrap"
        >
          <template #item.referred_user="{ item }">
            <div v-if="item.referred_user">
              <span class="font-weight-medium">{{ item.referred_user.name }}</span>
              <span class="text-medium-emphasis ms-1">({{ item.referred_user.email }})</span>
            </div>
          </template>

          <template #item.signup_ip="{ item }">
            <code v-if="item.signup_ip">{{ item.signup_ip }}</code>
            <span v-else>--</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>
        </VDataTable>

        <!-- Commissions Tab -->
        <VDataTable
          v-if="activeTab === 'commissions'"
          :headers="[
            { title: 'Amount', key: 'amount', sortable: true },
            { title: 'Type', key: 'type', sortable: true },
            { title: 'Status', key: 'status', sortable: true, align: 'center' },
            { title: 'Date', key: 'created_at', sortable: true },
          ]"
          :items="commissions.data"
          :items-per-page="10"
          hover
          class="text-no-wrap"
        >
          <template #item.amount="{ item }">
            <span class="font-weight-medium">${{ parseFloat(item.amount).toFixed(2) }}</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>
        </VDataTable>

        <!-- Payouts Tab -->
        <VDataTable
          v-if="activeTab === 'payouts'"
          :headers="[
            { title: 'Amount', key: 'amount', sortable: true },
            { title: 'Method', key: 'method', sortable: true },
            { title: 'Status', key: 'status', sortable: true, align: 'center' },
            { title: 'Reference', key: 'reference', sortable: false },
            { title: 'Date', key: 'created_at', sortable: true },
          ]"
          :items="payouts.data"
          :items-per-page="10"
          hover
          class="text-no-wrap"
        >
          <template #item.amount="{ item }">
            <span class="font-weight-medium">${{ parseFloat(item.amount).toFixed(2) }}</span>
          </template>

          <template #item.method="{ item }">
            {{ formatMethod(item.method) }}
          </template>

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

          <template #item.reference="{ item }">
            <code v-if="item.reference">{{ item.reference }}</code>
            <span v-else>--</span>
          </template>

          <template #item.created_at="{ item }">
            {{ formatDate(item.created_at) }}
          </template>
        </VDataTable>
      </VCardText>
    </VCard>
  </div>
</template>
