<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import { useTheme } from 'vuetify'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import StatCard from '@/Components/StatCard.vue'
import type { PaginatedResponse, StatusColor, WinbackCampaign, WinbackRecipient } from '@/types'

use([CanvasRenderer, BarChart, GridComponent, TooltipComponent])

interface Analytics {
  total_recipients: number
  total_emails_sent: number
  open_rate: number
  reactivation_rate: number
  reactivated_count: number
  unsubscribed_count: number
  total_opens: number
  total_clicks: number
}

interface Props {
  campaign: WinbackCampaign
  recipients: PaginatedResponse<WinbackRecipient>
  analytics: Analytics
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

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
}

function resolveRecipientStatus(recipient: WinbackRecipient): { label: string; color: StatusColor } {
  if (recipient.reactivated) return { label: 'Reactivated', color: 'success' }
  if (recipient.unsubscribed_at) return { label: 'Unsubscribed', color: 'error' }
  return { label: 'Active', color: 'info' }
}

const recipientHeaders = computed(() => [
  { title: 'Customer', key: 'user', sortable: false },
  { title: 'Status', key: 'status', sortable: false, align: 'center' as const },
  { title: 'Emails Sent', key: 'current_email_index', sortable: true, align: 'center' as const },
  { title: 'Last Email', key: 'last_email_sent_at', sortable: true },
  { title: 'Enrolled', key: 'created_at', sortable: true },
])

const theme = useTheme()
const isDark = computed<boolean>(() => theme.global.current.value.dark)
const chartTextColor = computed<string>(() => isDark.value ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.6)')

const funnelChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis' as const,
    backgroundColor: isDark.value ? 'rgba(30,41,59,0.95)' : 'rgba(255,255,255,0.95)',
    borderColor: isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)',
    textStyle: { color: isDark.value ? '#e2e8f0' : '#1e293b', fontSize: 12 },
  },
  grid: { left: 60, right: 20, top: 20, bottom: 30 },
  xAxis: {
    type: 'category' as const,
    data: ['Enrolled', 'Emailed', 'Opened', 'Reactivated'],
    axisLabel: { color: chartTextColor.value, fontSize: 11 },
    axisTick: { show: false },
  },
  yAxis: {
    type: 'value' as const,
    axisLabel: { color: chartTextColor.value, fontSize: 11 },
    splitLine: { lineStyle: { color: isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)' } },
  },
  series: [
    {
      type: 'bar',
      data: [
        { value: props.analytics.total_recipients, itemStyle: { color: '#3b82f6' } },
        { value: props.analytics.total_emails_sent, itemStyle: { color: '#8b5cf6' } },
        { value: props.analytics.total_opens, itemStyle: { color: '#f59e0b' } },
        { value: props.analytics.reactivated_count, itemStyle: { color: '#10b981' } },
      ],
      barWidth: '50%',
      label: {
        show: true,
        position: 'top' as const,
        color: chartTextColor.value,
        fontSize: 12,
        fontWeight: 'bold' as const,
      },
    },
  ],
}))

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}
</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="/winback-campaigns" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">{{ campaign.name }}</span>
          <VChip
            :color="resolveStatusColor(campaign.status)"
            size="small"
            class="text-capitalize ms-2"
          >
            {{ campaign.status }}
          </VChip>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Target: {{ campaign.cancellation_reason ?? 'All cancellations (catch-all)' }}
          <span v-if="campaign.offer_type !== 'none'" class="ms-2">
            | Offer: {{ resolveOfferLabel(campaign.offer_type) }}
            <span v-if="campaign.offer_value">
              ({{ campaign.offer_type === 'discount' ? `${campaign.offer_value}%` : `$${campaign.offer_value}` }})
            </span>
          </span>
        </div>
      </div>
      <Link :href="`/winback-campaigns/${campaign.id}/edit`">
        <VBtn color="primary" variant="outlined" prepend-icon="tabler-edit">
          Edit Campaign
        </VBtn>
      </Link>
    </div>

    <!-- Analytics Cards -->
    <VRow class="mb-2">
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Total Recipients"
          :stats="analytics.total_recipients"
          icon="tabler-users"
          color="primary"
        />
      </VCol>
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Emails Sent"
          :stats="analytics.total_emails_sent"
          icon="tabler-mail"
          color="info"
        />
      </VCol>
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Open Rate"
          :stats="`${analytics.open_rate}%`"
          icon="tabler-mail-opened"
          color="warning"
        />
      </VCol>
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Reactivation Rate"
          :stats="`${analytics.reactivation_rate}%`"
          icon="tabler-user-check"
          color="success"
        />
      </VCol>
    </VRow>

    <!-- Funnel Chart -->
    <VRow class="mb-6">
      <VCol cols="12">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-chart-bar" size="22" />
            <span>Campaign Funnel</span>
          </VCardTitle>
          <VCardText v-if="analytics.total_recipients === 0" class="text-center py-8">
            <VIcon icon="tabler-chart-bar-off" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No recipients enrolled yet.</div>
          </VCardText>
          <VCardText v-else class="pa-4">
            <VChart :option="funnelChartOption" autoresize style="height: 280px;" />
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Email Sequence -->
    <VCard class="mb-6">
      <VCardTitle class="d-flex align-center gap-2">
        <VIcon icon="tabler-list-numbers" size="22" />
        <span>Email Sequence ({{ campaign.email_sequence.length }} emails)</span>
      </VCardTitle>
      <VCardText>
        <VTimeline side="end" density="compact">
          <VTimelineItem
            v-for="(email, index) in campaign.email_sequence"
            :key="index"
            dot-color="primary"
            size="small"
          >
            <VCard variant="tonal">
              <VCardText>
                <div class="d-flex align-center gap-2 mb-1">
                  <VChip size="x-small" color="primary" variant="outlined">
                    Day {{ email.delay_days }}
                  </VChip>
                  <span class="text-body-2 font-weight-medium">{{ email.subject }}</span>
                </div>
                <div class="text-caption text-medium-emphasis">
                  {{ email.body.substring(0, 150) }}{{ email.body.length > 150 ? '...' : '' }}
                </div>
              </VCardText>
            </VCard>
          </VTimelineItem>
        </VTimeline>
      </VCardText>
    </VCard>

    <!-- Recipients Table -->
    <VCard>
      <VCardTitle class="d-flex align-center gap-2">
        <VIcon icon="tabler-users" size="22" />
        <span>Recipients</span>
      </VCardTitle>
      <VDataTable
        :headers="recipientHeaders"
        :items="recipients.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.user="{ item }">
          <div v-if="item.user" class="d-flex flex-column py-2">
            <span class="text-body-2 font-weight-medium">{{ item.user.name }}</span>
            <span class="text-caption text-medium-emphasis">{{ item.user.email }}</span>
          </div>
          <span v-else class="text-medium-emphasis">Deleted user</span>
        </template>

        <template #item.status="{ item }">
          <VChip
            :color="resolveRecipientStatus(item).color"
            size="small"
          >
            {{ resolveRecipientStatus(item).label }}
          </VChip>
        </template>

        <template #item.current_email_index="{ item }">
          <span class="font-weight-medium">
            {{ item.current_email_index }} / {{ campaign.email_sequence.length }}
          </span>
        </template>

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

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

        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-users" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No recipients enrolled in this campaign yet.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
