<script lang="ts" setup>
import { router } from '@inertiajs/vue3'
import { computed, ref, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
} 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 { CancellationSurvey, PaginatedResponse, StatusColor } from '@/types'

use([CanvasRenderer, PieChart, LineChart, GridComponent, TooltipComponent, LegendComponent])

interface ReasonBreakdown {
  reason: string
  count: number
}

interface MonthlyTrend {
  month: string
  count: number
}

interface Props {
  surveys: PaginatedResponse<CancellationSurvey>
  reasonBreakdown: ReasonBreakdown[]
  monthlyTrend: MonthlyTrend[]
  totalSurveys: number
  topReason: string
  wouldReturnRate: number
  availableReasons: string[]
  filters: {
    reason?: string
    date_from?: string
    date_to?: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const reasonFilter = ref<string>(props.filters.reason ?? 'all')
const dateFrom = ref<string>(props.filters.date_from ?? '')
const dateTo = ref<string>(props.filters.date_to ?? '')

function resolveWouldReturnColor(value: string | null): StatusColor {
  const map: Record<string, StatusColor> = {
    yes: 'success',
    maybe: 'warning',
    no: 'error',
  }
  return map[value ?? ''] ?? 'secondary'
}

const tableHeaders = computed(() => [
  { title: 'Customer', key: 'user', sortable: false },
  { title: 'Reason', key: 'cancellation_reason', sortable: true },
  { title: 'Feedback', key: 'cancellation_feedback', sortable: false },
  { title: 'Would Return', key: 'would_return', sortable: true, align: 'center' as const },
  { title: 'Plan', key: 'subscription', sortable: false },
  { title: 'Date', key: 'created_at', sortable: true },
])

function applyFilters(): void {
  router.get('/cancellation-surveys', {
    reason: reasonFilter.value === 'all' ? undefined : reasonFilter.value,
    date_from: dateFrom.value || undefined,
    date_to: dateTo.value || undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

let filterTimeout: ReturnType<typeof setTimeout> | null = null

watch([reasonFilter], () => {
  applyFilters()
})

watch([dateFrom, dateTo], () => {
  if (filterTimeout) clearTimeout(filterTimeout)
  filterTimeout = setTimeout(() => {
    applyFilters()
  }, 500)
})

const reasonOptions = computed(() => [
  { title: 'All Reasons', value: 'all' },
  ...props.availableReasons.map(r => ({ title: r, value: r })),
])

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 chartLineColor = computed<string>(() => isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)')

const pieColors = ['#3b82f6', '#ef4444', '#f59e0b', '#10b981', '#8b5cf6', '#ec4899', '#06b6d4']

const pieChartOption = computed(() => ({
  tooltip: {
    trigger: 'item' 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 },
    formatter: (params: { name: string; value: number; percent: number }) =>
      `<strong>${params.name}</strong><br/>Count: ${params.value} (${params.percent}%)`,
  },
  legend: {
    orient: 'vertical' as const,
    right: 10,
    top: 'center' as const,
    textStyle: { color: chartTextColor.value, fontSize: 11 },
  },
  series: [
    {
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['35%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 8, borderColor: isDark.value ? '#1e293b' : '#fff', borderWidth: 2 },
      label: { show: false },
      emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' as const } },
      data: props.reasonBreakdown.map((item, index) => ({
        value: item.count,
        name: item.reason,
        itemStyle: { color: pieColors[index % pieColors.length] },
      })),
    },
  ],
}))

function formatMonthLabel(monthStr: string): string {
  const [year, month] = monthStr.split('-')
  const date = new Date(parseInt(year), parseInt(month) - 1)
  return date.toLocaleDateString('en-US', { month: 'short', year: '2-digit' })
}

const trendChartOption = 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: 50, right: 20, top: 20, bottom: 30 },
  xAxis: {
    type: 'category' as const,
    data: props.monthlyTrend.map(r => formatMonthLabel(r.month)),
    axisLabel: { color: chartTextColor.value, fontSize: 11 },
    axisLine: { lineStyle: { color: chartLineColor.value } },
    axisTick: { show: false },
    boundaryGap: false,
  },
  yAxis: {
    type: 'value' as const,
    axisLabel: { color: chartTextColor.value, fontSize: 11 },
    splitLine: { lineStyle: { color: chartLineColor.value } },
  },
  series: [
    {
      type: 'line',
      data: props.monthlyTrend.map(r => r.count),
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: { width: 3, color: '#ef4444' },
      itemStyle: { color: '#ef4444' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(239,68,68,0.25)' },
            { offset: 1, color: 'rgba(239,68,68,0.02)' },
          ],
        },
      },
    },
  ],
}))

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="text-h4 font-weight-bold">
          Cancellation Surveys
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Understand why customers are leaving
        </div>
      </div>
    </div>

    <!-- Stats Cards -->
    <VRow class="mb-2">
      <VCol cols="12" sm="4">
        <StatCard
          title="Total Surveys"
          :stats="totalSurveys"
          icon="tabler-clipboard-data"
          color="primary"
        />
      </VCol>
      <VCol cols="12" sm="4">
        <StatCard
          title="Top Reason"
          :stats="topReason"
          icon="tabler-alert-triangle"
          color="warning"
        />
      </VCol>
      <VCol cols="12" sm="4">
        <StatCard
          title="Would Return Rate"
          :stats="`${wouldReturnRate}%`"
          icon="tabler-refresh"
          color="success"
        />
      </VCol>
    </VRow>

    <!-- Charts -->
    <VRow class="mb-6">
      <VCol cols="12" md="6">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-chart-pie" size="22" />
            <span>Reason Breakdown</span>
          </VCardTitle>
          <VCardText v-if="reasonBreakdown.length === 0" class="text-center py-8">
            <VIcon icon="tabler-chart-pie-off" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No survey data available.</div>
          </VCardText>
          <VCardText v-else class="pa-4">
            <VChart :option="pieChartOption" autoresize style="height: 300px;" />
          </VCardText>
        </VCard>
      </VCol>
      <VCol cols="12" md="6">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-chart-line" size="22" />
            <span>Cancellation Trend</span>
          </VCardTitle>
          <VCardText v-if="monthlyTrend.length === 0" class="text-center py-8">
            <VIcon icon="tabler-chart-line" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No trend data available.</div>
          </VCardText>
          <VCardText v-else class="pa-4">
            <VChart :option="trendChartOption" autoresize style="height: 300px;" />
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow align="center">
          <VCol cols="12" md="4">
            <VSelect
              v-model="reasonFilter"
              label="Cancellation Reason"
              :items="reasonOptions"
              density="compact"
              hide-details
            />
          </VCol>
          <VCol cols="12" md="4">
            <VTextField
              v-model="dateFrom"
              label="From Date"
              type="date"
              density="compact"
              hide-details
            />
          </VCol>
          <VCol cols="12" md="4">
            <VTextField
              v-model="dateTo"
              label="To Date"
              type="date"
              density="compact"
              hide-details
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Surveys Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="surveys.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.cancellation_reason="{ item }">
          <VChip size="small" variant="tonal" color="warning">
            {{ item.cancellation_reason }}
          </VChip>
        </template>

        <template #item.cancellation_feedback="{ item }">
          <span
            v-if="item.cancellation_feedback"
            class="text-truncate d-inline-block"
            style="max-width: 250px;"
            :title="item.cancellation_feedback"
          >
            {{ item.cancellation_feedback }}
          </span>
          <span v-else class="text-medium-emphasis">-</span>
        </template>

        <template #item.would_return="{ item }">
          <VChip
            v-if="item.would_return"
            :color="resolveWouldReturnColor(item.would_return)"
            size="small"
            class="text-capitalize"
          >
            {{ item.would_return }}
          </VChip>
          <span v-else class="text-medium-emphasis">-</span>
        </template>

        <template #item.subscription="{ item }">
          <span v-if="item.subscription">{{ item.subscription.type }}</span>
          <span v-else class="text-medium-emphasis">-</span>
        </template>

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

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