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

interface Props {
  payouts: PaginatedResponse<AffiliatePayout>
  affiliate: Affiliate
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const showPayoutDialog = ref<boolean>(false)
const payoutForm = useForm({
  method: 'paypal' as string,
})

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

const canRequestPayout = computed<boolean>(() => {
  return parseFloat(props.affiliate.pending_balance) >= parseFloat(props.affiliate.minimum_payout)
})

function submitPayout(): void {
  payoutForm.post('/affiliate/payouts', {
    onSuccess: () => {
      showPayoutDialog.value = false
      payoutForm.reset()
    },
  })
}

const tableHeaders = computed(() => [
  { title: 'Amount', key: 'amount', sortable: true },
  { title: 'Method', key: 'method', sortable: true },
  { title: 'Status', key: 'status', sortable: true, align: 'center' as const },
  { title: 'Reference', key: 'reference', sortable: false },
  { 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',
  })
}

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>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Payouts
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Request and track your affiliate payouts
        </div>
      </div>
      <VBtn
        color="primary"
        prepend-icon="tabler-cash-banknote"
        :disabled="!canRequestPayout"
        @click="showPayoutDialog = true"
      >
        Request Payout
      </VBtn>
    </div>

    <VAlert
      v-if="!canRequestPayout"
      type="info"
      variant="tonal"
      class="mb-6"
    >
      Your pending balance (${{ parseFloat(affiliate.pending_balance).toFixed(2) }}) is below the minimum payout threshold (${{ parseFloat(affiliate.minimum_payout).toFixed(2) }}).
    </VAlert>

    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="payouts.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>
        </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 class="text-medium-emphasis">--</span>
        </template>

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

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

    <!-- Request Payout Dialog -->
    <VDialog v-model="showPayoutDialog" max-width="500">
      <VCard>
        <VCardTitle>Request Payout</VCardTitle>
        <VCardText>
          <div class="text-body-1 mb-4">
            Available balance: <strong>${{ parseFloat(affiliate.pending_balance).toFixed(2) }}</strong>
          </div>
          <VSelect
            v-model="payoutForm.method"
            :items="[
              { title: 'PayPal', value: 'paypal' },
              { title: 'Account Credit', value: 'credit' },
              { title: 'Bank Transfer', value: 'bank_transfer' },
            ]"
            label="Payout Method"
            variant="outlined"
            :error-messages="payoutForm.errors.method"
          />
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" @click="showPayoutDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="primary"
            :loading="payoutForm.processing"
            @click="submitPayout"
          >
            Submit Request
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
