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

interface Props {
  coupon: Coupon
  redemptions: PaginatedResponse<CouponRedemption>
  stats: CouponRedemptionStats
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

function resolveCouponStatus(): { label: string; color: StatusColor } {
  if (!props.coupon.active) {
    return { label: 'Inactive', color: 'error' }
  }
  if (props.coupon.expires_at && new Date(props.coupon.expires_at) < new Date()) {
    return { label: 'Expired', color: 'secondary' }
  }
  if (props.coupon.max_uses !== null && props.coupon.times_used >= props.coupon.max_uses) {
    return { label: 'Exhausted', color: 'warning' }
  }
  return { label: 'Active', color: 'success' }
}

function formatValue(coupon: Coupon): string {
  if (coupon.type === 'percentage') {
    return `${parseFloat(coupon.value)}%`
  }
  return `$${parseFloat(coupon.value).toFixed(2)}`
}

function formatDate(dateString: string | null): string {
  if (!dateString) {
    return 'N/A'
  }
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function formatDateTime(dateString: string | null): string {
  if (!dateString) {
    return 'N/A'
  }
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  })
}

const couponStatus = computed(() => resolveCouponStatus())

const redemptionHeaders = computed(() => [
  { title: 'Customer', key: 'user', sortable: false },
  { title: 'Subscription', key: 'subscription', sortable: false },
  { title: 'Discount Applied', key: 'discount_amount', sortable: true, align: 'end' as const },
  { title: 'Redeemed At', key: 'created_at', sortable: true },
])

function resolveSubscriptionLabel(redemption: CouponRedemption): string {
  if (!redemption.subscription) {
    return 'N/A'
  }
  return `#${redemption.subscription.id} (${redemption.subscription.type})`
}

function resolveSubscriptionStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    active: 'success',
    canceled: 'error',
    past_due: 'warning',
    trialing: 'info',
    incomplete: 'secondary',
  }
  return map[status] ?? 'secondary'
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link href="/coupons" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Coupon Details</span>
          <VChip
            :color="couponStatus.color"
            size="small"
            class="ms-2"
          >
            {{ couponStatus.label }}
          </VChip>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Viewing coupon "{{ coupon.code }}"
        </div>
      </div>
      <Link :href="`/coupons/${coupon.id}/edit`">
        <VBtn color="primary" prepend-icon="tabler-edit">
          Edit Coupon
        </VBtn>
      </Link>
    </div>

    <VRow>
      <!-- Main Content -->
      <VCol cols="12" lg="8">
        <!-- Redemption Stats -->
        <VRow class="mb-6">
          <VCol cols="12" sm="4">
            <VCard>
              <VCardText class="d-flex align-center gap-4">
                <VAvatar color="primary" variant="tonal" size="48" rounded>
                  <VIcon icon="tabler-receipt" size="24" />
                </VAvatar>
                <div>
                  <div class="text-h5 font-weight-bold">
                    {{ stats.total_redemptions }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Total Redemptions
                  </div>
                </div>
              </VCardText>
            </VCard>
          </VCol>
          <VCol cols="12" sm="4">
            <VCard>
              <VCardText class="d-flex align-center gap-4">
                <VAvatar color="success" variant="tonal" size="48" rounded>
                  <VIcon icon="tabler-currency-dollar" size="24" />
                </VAvatar>
                <div>
                  <div class="text-h5 font-weight-bold">
                    ${{ stats.total_discount.toFixed(2) }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Total Discount Given
                  </div>
                </div>
              </VCardText>
            </VCard>
          </VCol>
          <VCol cols="12" sm="4">
            <VCard>
              <VCardText class="d-flex align-center gap-4">
                <VAvatar color="info" variant="tonal" size="48" rounded>
                  <VIcon icon="tabler-clock" size="24" />
                </VAvatar>
                <div>
                  <div class="text-h5 font-weight-bold">
                    {{ formatDate(stats.latest_redemption) }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Last Redemption
                  </div>
                </div>
              </VCardText>
            </VCard>
          </VCol>
        </VRow>

        <!-- Redemption History Table -->
        <VCard title="Redemption History">
          <VDataTable
            :headers="redemptionHeaders"
            :items="redemptions.data"
            :items-per-page="25"
            hover
            class="text-no-wrap"
          >
            <!-- Customer -->
            <template #item.user="{ item }">
              <div v-if="item.user" class="d-flex flex-column py-2">
                <Link :href="`/customers/${item.user.id}`" class="text-decoration-none">
                  <span class="text-body-2 font-weight-medium text-primary">{{ item.user.name }}</span>
                </Link>
                <span class="text-caption text-medium-emphasis">{{ item.user.email }}</span>
              </div>
              <span v-else class="text-medium-emphasis">
                Deleted User
              </span>
            </template>

            <!-- Subscription -->
            <template #item.subscription="{ item }">
              <template v-if="item.subscription">
                <span class="font-weight-medium">{{ resolveSubscriptionLabel(item) }}</span>
                <VChip
                  :color="resolveSubscriptionStatusColor(item.subscription.stripe_status)"
                  size="x-small"
                  variant="tonal"
                  class="ms-2 text-capitalize"
                >
                  {{ item.subscription.stripe_status }}
                </VChip>
              </template>
              <span v-else class="text-medium-emphasis">N/A</span>
            </template>

            <!-- Discount Amount -->
            <template #item.discount_amount="{ item }">
              <span class="font-weight-medium text-success">
                -${{ parseFloat(item.discount_amount).toFixed(2) }}
              </span>
            </template>

            <!-- Redeemed At -->
            <template #item.created_at="{ item }">
              {{ formatDateTime(item.created_at) }}
            </template>

            <!-- No data -->
            <template #no-data>
              <div class="text-center py-8">
                <VIcon icon="tabler-receipt-off" size="48" color="disabled" class="mb-2" />
                <div class="text-medium-emphasis">
                  No redemptions for this coupon yet.
                </div>
              </div>
            </template>

            <!-- Bottom pagination info -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-space-between pa-4">
                <div class="text-body-2 text-medium-emphasis">
                  Showing {{ redemptions.from ?? 0 }} to {{ redemptions.to ?? 0 }} of {{ redemptions.total }} redemptions
                </div>
                <div v-if="redemptions.last_page > 1" class="d-flex gap-2">
                  <template v-for="link in redemptions.links" :key="link.label">
                    <Link
                      v-if="link.url"
                      :href="link.url"
                      class="text-decoration-none"
                      preserve-scroll
                    >
                      <VBtn
                        :variant="link.active ? 'flat' : 'text'"
                        :color="link.active ? 'primary' : undefined"
                        size="small"
                        min-width="36"
                      >
                        <span v-html="link.label" />
                      </VBtn>
                    </Link>
                    <VBtn
                      v-else
                      variant="text"
                      size="small"
                      min-width="36"
                      disabled
                    >
                      <span v-html="link.label" />
                    </VBtn>
                  </template>
                </div>
              </div>
            </template>
          </VDataTable>
        </VCard>
      </VCol>

      <!-- Sidebar -->
      <VCol cols="12" lg="4">
        <!-- Coupon Info -->
        <VCard title="Coupon Info" class="mb-6">
          <VCardText>
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Code</span>
              <span class="font-weight-medium font-monospace">{{ coupon.code }}</span>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Status</span>
              <VChip
                :color="couponStatus.color"
                size="small"
              >
                {{ couponStatus.label }}
              </VChip>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Type</span>
              <VChip
                :color="coupon.type === 'percentage' ? 'info' : 'warning'"
                size="small"
                variant="tonal"
                class="text-capitalize"
              >
                {{ coupon.type }}
              </VChip>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Value</span>
              <span class="text-body-2 font-weight-medium">{{ formatValue(coupon) }}</span>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Usage</span>
              <span class="text-body-2 font-weight-medium">
                {{ coupon.times_used }} / {{ coupon.max_uses ?? '&infin;' }}
              </span>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Expires</span>
              <span
                class="text-body-2"
                :class="{ 'text-error': coupon.expires_at && new Date(coupon.expires_at) < new Date() }"
              >
                {{ coupon.expires_at ? formatDate(coupon.expires_at) : 'Never' }}
              </span>
            </div>
            <VDivider class="mb-4" />
            <div class="d-flex justify-space-between align-center">
              <span class="text-body-2 text-medium-emphasis">Created</span>
              <span class="text-body-2">{{ formatDate(coupon.created_at) }}</span>
            </div>
          </VCardText>
        </VCard>

        <!-- Plan Restrictions -->
        <VCard title="Plan Restrictions" class="mb-6">
          <VCardText>
            <div v-if="!coupon.applies_to || coupon.applies_to.length === 0" class="text-body-2 text-medium-emphasis">
              Applies to all plans (no restrictions).
            </div>
            <div v-else>
              <VChip
                v-for="planId in coupon.applies_to"
                :key="planId"
                size="small"
                variant="tonal"
                color="secondary"
                class="me-2 mb-2"
              >
                Plan #{{ planId }}
              </VChip>
            </div>
          </VCardText>
        </VCard>

        <!-- Actions -->
        <VCard>
          <VCardText>
            <Link :href="`/coupons/${coupon.id}/edit`" class="text-decoration-none">
              <VBtn
                color="primary"
                block
                prepend-icon="tabler-edit"
                class="mb-3"
              >
                Edit Coupon
              </VBtn>
            </Link>
            <Link href="/coupons" class="text-decoration-none">
              <VBtn
                variant="outlined"
                block
              >
                Back to List
              </VBtn>
            </Link>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>
