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

interface Props {
  affiliate: Affiliate | null
  stats: AffiliateStats | null
  monthlyChart?: MonthlyChartEntry[]
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const applyForm = useForm({})
const copied = ref<boolean>(false)

const referralUrl = computed<string>(() => {
  if (!props.affiliate) return ''
  return `${window.location.origin}?ref=${props.affiliate.referral_code}`
})

function copyReferralLink(): void {
  navigator.clipboard.writeText(referralUrl.value)
  copied.value = true
  setTimeout(() => { copied.value = false }, 2000)
}

function submitApplication(): void {
  applyForm.post('/affiliate/apply')
}

const chartOption = computed(() => {
  if (!props.monthlyChart?.length) return null
  return {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: props.monthlyChart.map(e => e.month),
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '${value}' },
    },
    series: [{
      data: props.monthlyChart.map(e => parseFloat(e.total)),
      type: 'bar',
      color: '#1d4ed8',
      barWidth: '60%',
    }],
  }
})
</script>

<template>
  <div>
    <div class="text-h4 font-weight-bold mb-2">
      Affiliate Program
    </div>
    <div class="text-body-2 text-medium-emphasis mb-6">
      Earn commissions by referring new customers to EZSCALE
    </div>

    <!-- Not yet an affiliate -->
    <VCard v-if="!affiliate" class="pa-8 text-center">
      <VIcon icon="tabler-affiliate" size="64" color="primary" class="mb-4" />
      <div class="text-h5 font-weight-bold mb-2">
        Join the EZSCALE Affiliate Program
      </div>
      <div class="text-body-1 text-medium-emphasis mb-6" style="max-width: 500px; margin: 0 auto;">
        Earn commissions for every customer you refer. Share your unique referral link and start earning today.
      </div>
      <VBtn
        color="primary"
        size="large"
        :loading="applyForm.processing"
        @click="submitApplication"
      >
        Apply Now
      </VBtn>
    </VCard>

    <!-- Pending approval -->
    <VAlert
      v-else-if="affiliate.status === 'pending'"
      type="info"
      variant="tonal"
      prominent
      class="mb-6"
    >
      <VAlertTitle>Application Pending</VAlertTitle>
      Your affiliate application is under review. You will be notified once it is approved.
    </VAlert>

    <!-- Suspended -->
    <VAlert
      v-else-if="affiliate.status === 'suspended'"
      type="error"
      variant="tonal"
      prominent
      class="mb-6"
    >
      <VAlertTitle>Account Suspended</VAlertTitle>
      Your affiliate account has been suspended. Please contact support for more information.
    </VAlert>

    <!-- Active affiliate -->
    <template v-if="affiliate && affiliate.status === 'active' && stats">
      <!-- Referral Link -->
      <VCard class="mb-6">
        <VCardTitle class="d-flex align-center gap-2">
          <VIcon icon="tabler-link" />
          Your Referral Link
        </VCardTitle>
        <VCardText>
          <div class="d-flex align-center gap-3">
            <VTextField
              :model-value="referralUrl"
              readonly
              variant="outlined"
              density="comfortable"
              hide-details
              class="flex-grow-1"
            />
            <VBtn
              :color="copied ? 'success' : 'primary'"
              :prepend-icon="copied ? 'tabler-check' : 'tabler-copy'"
              @click="copyReferralLink"
            >
              {{ copied ? 'Copied!' : 'Copy' }}
            </VBtn>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-2">
            Referral code: <code>{{ affiliate.referral_code }}</code>
            &mdash; Commission: {{ affiliate.commission_type === 'percentage' ? `${affiliate.commission_rate}%` : `$${affiliate.commission_rate}` }}
            {{ affiliate.recurring_commissions ? '(recurring)' : '(one-time)' }}
          </div>
        </VCardText>
      </VCard>

      <!-- Stats Cards -->
      <VRow class="mb-6">
        <VCol cols="12" sm="6" md="3">
          <VCard>
            <VCardText class="text-center">
              <VIcon icon="tabler-cash" size="32" color="success" class="mb-2" />
              <div class="text-h5 font-weight-bold">
                ${{ stats.total_earned.toFixed(2) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Total Earned
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" md="3">
          <VCard>
            <VCardText class="text-center">
              <VIcon icon="tabler-clock-dollar" size="32" color="warning" class="mb-2" />
              <div class="text-h5 font-weight-bold">
                ${{ stats.pending_balance.toFixed(2) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Pending Balance
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" md="3">
          <VCard>
            <VCardText class="text-center">
              <VIcon icon="tabler-wallet" size="32" color="primary" class="mb-2" />
              <div class="text-h5 font-weight-bold">
                ${{ stats.total_paid.toFixed(2) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Total Paid
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" md="3">
          <VCard>
            <VCardText class="text-center">
              <VIcon icon="tabler-users" size="32" color="info" class="mb-2" />
              <div class="text-h5 font-weight-bold">
                {{ stats.referral_count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Referrals
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <!-- Monthly Chart -->
      <VCard v-if="chartOption" class="mb-6">
        <VCardTitle>Monthly Earnings</VCardTitle>
        <VCardText>
          <VueEcharts :option="chartOption" style="height: 300px;" />
        </VCardText>
      </VCard>

      <!-- Quick Links -->
      <VRow>
        <VCol cols="12" sm="4">
          <Link href="/affiliate/referrals" class="text-decoration-none">
            <VCard hover>
              <VCardText class="d-flex align-center gap-3">
                <VIcon icon="tabler-users-group" size="28" color="primary" />
                <div>
                  <div class="text-body-1 font-weight-medium">
                    Referrals
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    View referral history
                  </div>
                </div>
                <VSpacer />
                <VIcon icon="tabler-chevron-right" />
              </VCardText>
            </VCard>
          </Link>
        </VCol>
        <VCol cols="12" sm="4">
          <Link href="/affiliate/commissions" class="text-decoration-none">
            <VCard hover>
              <VCardText class="d-flex align-center gap-3">
                <VIcon icon="tabler-coins" size="28" color="success" />
                <div>
                  <div class="text-body-1 font-weight-medium">
                    Commissions
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    View commission history
                  </div>
                </div>
                <VSpacer />
                <VIcon icon="tabler-chevron-right" />
              </VCardText>
            </VCard>
          </Link>
        </VCol>
        <VCol cols="12" sm="4">
          <Link href="/affiliate/payouts" class="text-decoration-none">
            <VCard hover>
              <VCardText class="d-flex align-center gap-3">
                <VIcon icon="tabler-cash-banknote" size="28" color="warning" />
                <div>
                  <div class="text-body-1 font-weight-medium">
                    Payouts
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    View payout history
                  </div>
                </div>
                <VSpacer />
                <VIcon icon="tabler-chevron-right" />
              </VCardText>
            </VCard>
          </Link>
        </VCol>
      </VRow>
    </template>
  </div>
</template>
