<script lang="ts" setup>
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { 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'

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

interface RevenueMonth {
  month: string
  total: number
  transactions: number
  avg_amount: number
}

interface Props {
  totalCustomers: number
  newCustomersThisMonth: number
  mrr: number
  invoiceMrr: number
  mrrChangePercent: number | null
  arr: number
  activeServices: number
  serviceBreakdown: Record<string, number>
  totalTransactionRevenue: number
  estimatedFees: number
  netRevenue: number
  revenueThisMonth: number
  overdueCount: number
  overdueAmount: number
  currentChurnRate: number
  churnHealthStatus: 'healthy' | 'watch' | 'high'
  revenueByMonth: RevenueMonth[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

function formatCurrency(value: number | string): string {
  const num = typeof value === 'string' ? parseFloat(value) : value
  return `$${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

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 serviceBreakdownText = computed<string>(() => {
  const labels: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated',
    web_hosting: 'Web',
    game: 'Game',
  }
  return Object.entries(props.serviceBreakdown)
    .map(([type, count]) => `${count} ${labels[type] ?? type}`)
    .join(' · ') || 'No active services'
})

const mrrChangeText = computed<string | undefined>(() => {
  if (props.mrrChangePercent === null) return undefined
  const sign = props.mrrChangePercent >= 0 ? '+' : ''
  return `${sign}${props.mrrChangePercent}% MoM`
})

const mrrChangeColor = computed<string | undefined>(() => {
  if (props.mrrChangePercent === null) return undefined
  return props.mrrChangePercent >= 0 ? 'success' : 'error'
})

const churnBadgeLabel = computed<string>(() => {
  const map: Record<string, string> = { healthy: 'Healthy', watch: 'Watch', high: 'High' }
  return map[props.churnHealthStatus] ?? props.churnHealthStatus
})

const churnBadgeColor = computed<string>(() => {
  const map: Record<string, string> = { healthy: 'success', watch: 'warning', high: 'error' }
  return map[props.churnHealthStatus] ?? 'secondary'
})

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 revenueChartOption = 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 },
    formatter: (params: Array<{ seriesName: string; value: number; marker: string; axisValue: string }>) => {
      let html = `<div style="font-weight:600;margin-bottom:6px">${params[0].axisValue}</div>`
      for (const p of params) {
        const val = p.seriesName === 'Transactions'
          ? p.value.toString()
          : `$${p.value.toLocaleString('en-US', { minimumFractionDigits: 2 })}`
        html += `<div style="display:flex;justify-content:space-between;gap:16px">${p.marker} ${p.seriesName}<span style="font-weight:600">${val}</span></div>`
      }
      return html
    },
  },
  legend: {
    data: ['Revenue', 'Transactions', 'Avg Transaction'],
    textStyle: { color: chartTextColor.value, fontSize: 11 },
    bottom: 0,
    icon: 'roundRect',
    itemWidth: 14,
    itemHeight: 8,
  },
  grid: { left: 70, right: 60, top: 20, bottom: 40 },
  xAxis: {
    type: 'category' as const,
    data: props.revenueByMonth.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,
        formatter: (v: number) => v >= 1000 ? `$${(v / 1000).toFixed(0)}k` : `$${v}`,
      },
      splitLine: { lineStyle: { color: chartLineColor.value } },
    },
    {
      type: 'value' as const,
      axisLabel: { color: chartTextColor.value, fontSize: 11 },
      splitLine: { show: false },
    },
  ],
  series: [
    {
      name: 'Revenue',
      type: 'line',
      data: props.revenueByMonth.map(r => r.total),
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: { width: 3, color: '#3b82f6' },
      itemStyle: { color: '#3b82f6' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(59,130,246,0.25)' },
            { offset: 1, color: 'rgba(59,130,246,0.02)' },
          ],
        },
      },
    },
    {
      name: 'Transactions',
      type: 'line',
      yAxisIndex: 1,
      data: props.revenueByMonth.map(r => r.transactions),
      smooth: true,
      symbol: 'diamond',
      symbolSize: 6,
      lineStyle: { width: 2, color: '#10b981', type: 'dashed' as const },
      itemStyle: { color: '#10b981' },
    },
    {
      name: 'Avg Transaction',
      type: 'line',
      data: props.revenueByMonth.map(r => r.avg_amount),
      smooth: true,
      symbol: 'triangle',
      symbolSize: 6,
      lineStyle: { width: 2, color: '#f59e0b' },
      itemStyle: { color: '#f59e0b' },
    },
  ],
}))
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">Admin Dashboard</div>
        <div class="text-body-2 text-medium-emphasis">
          Overview of your business metrics
        </div>
      </div>
    </div>

    <!-- Row 1: Core Financial Metrics -->
    <VRow class="mb-2">
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Total Customers"
          :stats="totalCustomers"
          icon="tabler-users"
          color="primary"
          :subtitle="`+${newCustomersThisMonth} this month`"
          subtitle-color="success"
          href="/customers"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="MRR"
          :stats="formatCurrency(mrr)"
          icon="tabler-currency-dollar"
          color="success"
          :subtitle="mrrChangeText"
          :subtitle-color="mrrChangeColor"
          href="/transactions"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Collected (30d)"
          :stats="formatCurrency(invoiceMrr)"
          icon="tabler-receipt"
          color="info"
          subtitle="Paid invoices"
          href="/invoices"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Annual Recurring Revenue"
          :stats="formatCurrency(arr)"
          icon="tabler-calendar-dollar"
          color="primary"
          href="/transactions"
        />
      </VCol>
    </VRow>

    <!-- Row 2: Operational Metrics -->
    <VRow class="mb-2">
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Active Services"
          :stats="activeServices"
          icon="tabler-server"
          color="warning"
          :subtitle="serviceBreakdownText"
          href="/services"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Net Revenue"
          :stats="formatCurrency(netRevenue)"
          icon="tabler-trending-up"
          color="success"
          :subtitle="`Fees: ${formatCurrency(estimatedFees)}`"
          subtitle-color="warning"
          href="/transactions"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Overdue Invoices"
          :stats="`${overdueCount} (${formatCurrency(overdueAmount)})`"
          icon="tabler-alert-circle"
          :color="overdueCount > 0 ? 'error' : 'success'"
          href="/invoices?status=overdue"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Churn Rate"
          :stats="`${currentChurnRate}%`"
          icon="tabler-user-minus"
          :color="churnBadgeColor"
          :badge="churnBadgeLabel"
          :badge-color="churnBadgeColor"
        />
      </VCol>
    </VRow>

    <!-- Row 3: Revenue Trend -->
    <VRow>
      <VCol cols="12">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-chart-bar" size="22" />
              <span>Revenue Trend (12 Months)</span>
            </div>
            <VChip size="small" color="success" variant="tonal">
              Payment Transactions
            </VChip>
          </VCardTitle>

          <VCardText v-if="revenueByMonth.length === 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 revenue data available for the last 12 months.</div>
          </VCardText>

          <VCardText v-else class="pa-4">
            <VChart :option="revenueChartOption" autoresize style="height: 360px;" />
          </VCardText>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>
