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

interface Props {
  redemptions: PaginatedResponse<CouponRedemption>
  coupons: Coupon[]
  stats: {
    total_redemptions: number
    total_discount: number
    unique_customers: number
    unique_coupons: number
  }
  filters: {
    coupon_id?: number | string
    customer?: string
    date_from?: string
    date_to?: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

// Filter form state
const filterForm = ref({
  coupon_id: props.filters.coupon_id ?? '',
  customer: props.filters.customer ?? '',
  date_from: props.filters.date_from ?? '',
  date_to: props.filters.date_to ?? '',
})

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

function applyFilters(): void {
  router.get('/coupons/redemptions', filterForm.value, {
    preserveState: true,
    preserveScroll: true,
  })
}

function clearFilters(): void {
  filterForm.value = {
    coupon_id: '',
    customer: '',
    date_from: '',
    date_to: '',
  }
  router.get('/coupons/redemptions', {}, {
    preserveState: true,
    preserveScroll: true,
  })
}

function exportToCSV(): void {
  // Build query string with current filters
  const params = new URLSearchParams()
  if (filterForm.value.coupon_id) {
    params.append('coupon_id', String(filterForm.value.coupon_id))
  }
  if (filterForm.value.customer) {
    params.append('customer', filterForm.value.customer)
  }
  if (filterForm.value.date_from) {
    params.append('date_from', filterForm.value.date_from)
  }
  if (filterForm.value.date_to) {
    params.append('date_to', filterForm.value.date_to)
  }
  params.append('export', 'csv')

  window.location.href = `/coupons/redemptions?${params.toString()}`
}

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',
    hour: 'numeric',
    minute: '2-digit',
  })
}

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

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'
}

function resolveCouponTypeColor(type: string): StatusColor {
  return type === 'percentage' ? 'info' : 'warning'
}

const hasActiveFilters = computed(() => {
  return !!(filterForm.value.coupon_id || filterForm.value.customer || filterForm.value.date_from || filterForm.value.date_to)
})
</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 Redemption History</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          View all coupon redemptions across all coupons
        </div>
      </div>
      <VBtn
        color="success"
        prepend-icon="tabler-download"
        @click="exportToCSV"
      >
        Export CSV
      </VBtn>
    </div>

    <!-- Stats Cards -->
    <VRow class="mb-6">
      <VCol cols="12" sm="6" lg="3">
        <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="6" lg="3">
        <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="6" lg="3">
        <VCard>
          <VCardText class="d-flex align-center gap-4">
            <VAvatar color="info" variant="tonal" size="48" rounded>
              <VIcon icon="tabler-users" size="24" />
            </VAvatar>
            <div>
              <div class="text-h5 font-weight-bold">
                {{ stats.unique_customers }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Unique Customers
              </div>
            </div>
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" sm="6" lg="3">
        <VCard>
          <VCardText class="d-flex align-center gap-4">
            <VAvatar color="warning" variant="tonal" size="48" rounded>
              <VIcon icon="tabler-discount-2" size="24" />
            </VAvatar>
            <div>
              <div class="text-h5 font-weight-bold">
                {{ stats.unique_coupons }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Coupons Used
              </div>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <div class="text-subtitle-1 font-weight-medium mb-4">
          Filters
        </div>
        <VRow>
          <VCol cols="12" md="3">
            <VSelect
              v-model="filterForm.coupon_id"
              :items="coupons"
              item-title="code"
              item-value="id"
              label="Coupon"
              clearable
              density="comfortable"
            />
          </VCol>
          <VCol cols="12" md="3">
            <VTextField
              v-model="filterForm.customer"
              label="Customer"
              placeholder="Name or email"
              clearable
              density="comfortable"
            />
          </VCol>
          <VCol cols="12" md="2">
            <VTextField
              v-model="filterForm.date_from"
              label="From Date"
              type="date"
              clearable
              density="comfortable"
            />
          </VCol>
          <VCol cols="12" md="2">
            <VTextField
              v-model="filterForm.date_to"
              label="To Date"
              type="date"
              clearable
              density="comfortable"
            />
          </VCol>
          <VCol cols="12" md="2" class="d-flex align-center gap-2">
            <VBtn
              color="primary"
              block
              @click="applyFilters"
            >
              Apply
            </VBtn>
            <VBtn
              v-if="hasActiveFilters"
              variant="outlined"
              color="secondary"
              block
              @click="clearFilters"
            >
              Clear
            </VBtn>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Redemptions Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="redemptions.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <!-- Coupon -->
        <template #item.coupon="{ item }">
          <div v-if="item.coupon" class="d-flex flex-column py-2">
            <Link :href="`/coupons/${item.coupon.id}`" class="text-decoration-none">
              <span class="text-body-2 font-weight-medium font-monospace text-primary">{{ item.coupon.code }}</span>
            </Link>
            <div class="d-flex align-center gap-2 mt-1">
              <VChip
                :color="resolveCouponTypeColor(item.coupon.type)"
                size="x-small"
                variant="tonal"
                class="text-capitalize"
              >
                {{ item.coupon.type }}
              </VChip>
              <span class="text-caption text-medium-emphasis">
                {{ formatCouponValue(item.coupon) }}
              </span>
            </div>
          </div>
          <span v-else class="text-medium-emphasis">
            Deleted Coupon
          </span>
        </template>

        <!-- 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">#{{ item.subscription.id }}</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 }">
          {{ formatDate(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">
              {{ hasActiveFilters ? 'No redemptions found with the selected filters.' : 'No coupon redemptions yet.' }}
            </div>
          </div>
        </template>

        <!-- Bottom pagination -->
        <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>
  </div>
</template>
