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

interface Props {
  campaigns: PaginatedResponse<WinbackCampaign>
  filters: {
    status: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const activeTab = ref<string>(props.filters.status)

const statusTabs: { title: string; value: string }[] = [
  { title: 'All', value: 'all' },
  { title: 'Active', value: 'active' },
  { title: 'Paused', value: 'paused' },
  { title: 'Archived', value: 'archived' },
]

function resolveStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    active: 'success',
    paused: 'warning',
    archived: 'secondary',
  }
  return map[status] ?? 'secondary'
}

function resolveOfferLabel(type: string): string {
  const map: Record<string, string> = {
    discount: 'Discount',
    credit: 'Credit',
    free_upgrade: 'Free Upgrade',
    none: 'None',
  }
  return map[type] ?? type
}

const tableHeaders = computed(() => [
  { title: 'Campaign', key: 'name', sortable: true },
  { title: 'Reason', key: 'cancellation_reason', sortable: true },
  { title: 'Status', key: 'status', sortable: true, align: 'center' as const },
  { title: 'Offer', key: 'offer_type', sortable: true },
  { title: 'Recipients', key: 'recipients_count', sortable: true, align: 'center' as const },
  { title: 'Reactivation Rate', key: 'reactivation_rate', sortable: true, align: 'center' as const },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
])

watch(activeTab, () => {
  router.get('/winback-campaigns', {
    status: activeTab.value,
  }, {
    preserveState: true,
    replace: true,
  })
})

function archiveCampaign(campaign: WinbackCampaign): void {
  if (confirm(`Are you sure you want to archive "${campaign.name}"?`)) {
    router.delete(`/winback-campaigns/${campaign.id}`, {
      preserveScroll: true,
    })
  }
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Win-back Campaigns
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage campaigns to re-engage cancelled customers
        </div>
      </div>
      <Link href="/winback-campaigns/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Create Campaign
        </VBtn>
      </Link>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VTabs v-model="activeTab" density="comfortable">
          <VTab
            v-for="tab in statusTabs"
            :key="tab.value"
            :value="tab.value"
          >
            {{ tab.title }}
          </VTab>
        </VTabs>
      </VCardText>
    </VCard>

    <!-- Campaigns Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="campaigns.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.name="{ item }">
          <Link :href="`/winback-campaigns/${item.id}`" class="text-decoration-none">
            <span class="text-body-1 font-weight-medium text-primary">{{ item.name }}</span>
          </Link>
        </template>

        <template #item.cancellation_reason="{ item }">
          <span v-if="item.cancellation_reason">{{ item.cancellation_reason }}</span>
          <VChip v-else size="small" variant="tonal" color="info">
            Catch-all
          </VChip>
        </template>

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

        <template #item.offer_type="{ item }">
          <span>{{ resolveOfferLabel(item.offer_type) }}</span>
          <span v-if="item.offer_value && item.offer_type !== 'none'" class="text-medium-emphasis ms-1">
            ({{ item.offer_type === 'discount' ? `${item.offer_value}%` : `$${item.offer_value}` }})
          </span>
        </template>

        <template #item.recipients_count="{ item }">
          <span class="font-weight-medium">{{ item.recipients_count ?? 0 }}</span>
        </template>

        <template #item.reactivation_rate="{ item }">
          <VChip
            :color="(item.reactivation_rate ?? 0) > 10 ? 'success' : (item.reactivation_rate ?? 0) > 0 ? 'warning' : 'secondary'"
            size="small"
            variant="tonal"
          >
            {{ item.reactivation_rate ?? 0 }}%
          </VChip>
        </template>

        <template #item.actions="{ item }">
          <VMenu>
            <template #activator="{ props: menuProps }">
              <VBtn
                icon="tabler-dots-vertical"
                variant="text"
                size="small"
                v-bind="menuProps"
              />
            </template>
            <VList density="compact">
              <Link :href="`/winback-campaigns/${item.id}`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-eye">
                  <VListItemTitle>View</VListItemTitle>
                </VListItem>
              </Link>
              <Link :href="`/winback-campaigns/${item.id}/edit`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-edit">
                  <VListItemTitle>Edit</VListItemTitle>
                </VListItem>
              </Link>
              <VListItem
                v-if="item.status !== 'archived'"
                prepend-icon="tabler-archive"
                @click="archiveCampaign(item)"
              >
                <VListItemTitle>Archive</VListItemTitle>
              </VListItem>
            </VList>
          </VMenu>
        </template>

        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-mail-forward" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No win-back campaigns found.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
