<script lang="ts" setup>
import { computed } from 'vue'
import { Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import StatCard from '@/Components/StatCard.vue'
import { resolveInvoiceStatusColor, resolveSubscriptionStatusColor } from '@/utils/resolvers'

interface RecentInvoice {
  id: number
  number: string
  total: string
  status: string
  gateway: string
  created_at: string
  user: {
    id: number
    name: string
    email: string
  } | null
}

interface RecentSubscription {
  id: number
  user_id: number
  plan_id: number | null
  type: string
  stripe_status: string
  gateway: string
  created_at: string
  plan_name: string | null
  plan_price: string | null
  plan_billing_cycle: string | null
  user_name: string | null
  user_email: string | null
}

interface PopularPlan {
  id: number
  name: string
  service_type: string
  price: string
  billing_cycle: string
  active_services_count: number
}

interface RevenueByServiceType {
  service_type: string
  revenue: string
  invoice_count: number
}

interface RevenueMonth {
  month: string
  total: number
}

interface CustomerGrowthMonth {
  month: string
  count: number
}

interface ChurnMonth {
  month: string
  rate: number
  cancelled: number
}

interface OverdueInvoice {
  id: number
  user_id: number
  number: string
  total: string
  due_date: string
  status: string
  user: {
    id: number
    name: string
    email: string
  } | null
}

interface Props {
  totalCustomers: number
  mrr: number
  totalRevenue: number
  activeServices: number
  pendingInvoicesCount: number
  pendingInvoicesAmount: number
  overdueCount: number
  overdueAmount: number
  recentInvoices: RecentInvoice[]
  recentSubscriptions: RecentSubscription[]
  popularPlans: PopularPlan[]
  revenueByServiceType: RevenueByServiceType[]
  newCustomersThisMonth: number
  revenueThisMonth: number
  arr: number
  revenueByMonth: RevenueMonth[]
  customerGrowth: CustomerGrowthMonth[]
  churnData: ChurnMonth[]
  overdueInvoices: OverdueInvoice[]
}

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 formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}

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

function resolveServiceTypeColor(type: string): string {
  const map: Record<string, string> = {
    vps: 'primary',
    dedicated: 'info',
    web_hosting: 'success',
    game: 'warning',
  }
  return map[type] ?? 'secondary'
}

function resolveServiceTypeIcon(type: string): string {
  const map: Record<string, string> = {
    vps: 'tabler-server',
    dedicated: 'tabler-server-2',
    web_hosting: 'tabler-world',
    game: 'tabler-device-gamepad-2',
  }
  return map[type] ?? 'tabler-box'
}

function formatServiceType(type: string): string {
  const map: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated',
    web_hosting: 'Web Hosting',
    game: 'Game Hosting',
  }
  return map[type] ?? type
}

function resolveChurnColor(rate: number): string {
  if (rate < 2) return 'success'
  if (rate <= 5) return 'warning'
  return 'error'
}

function daysOverdue(dueDateStr: string): number {
  const due = new Date(dueDateStr)
  const now = new Date()
  const diff = Math.floor((now.getTime() - due.getTime()) / (1000 * 60 * 60 * 24))
  return Math.max(0, diff)
}

const maxRevenue = computed<number>(() => {
  if (props.revenueByMonth.length === 0) return 1
  return Math.max(...props.revenueByMonth.map(r => r.total), 1)
})

const totalCustomerGrowth = computed<number>(() => {
  return props.customerGrowth.reduce((sum, row) => sum + row.count, 0)
})

const maxCustomerGrowth = computed<number>(() => {
  if (props.customerGrowth.length === 0) return 1
  return Math.max(...props.customerGrowth.map(r => r.count), 1)
})
</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 and recent activity
        </div>
      </div>
    </div>

    <!-- Row 1: Key Metrics -->
    <VRow class="mb-2">
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Total Customers"
          :stats="totalCustomers"
          icon="tabler-users"
          color="primary"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Monthly Recurring Revenue"
          :stats="formatCurrency(mrr)"
          icon="tabler-currency-dollar"
          color="success"
        />
      </VCol>

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

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Active Services"
          :stats="activeServices"
          icon="tabler-server"
          color="warning"
        />
      </VCol>
    </VRow>

    <!-- Row 1b: Secondary Metrics -->
    <VRow class="mb-2">
      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Total Revenue"
          :stats="formatCurrency(totalRevenue)"
          icon="tabler-trending-up"
          color="success"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Revenue This Month"
          :stats="formatCurrency(revenueThisMonth)"
          icon="tabler-report-money"
          color="primary"
        />
      </VCol>

      <VCol cols="12" sm="6" lg="3">
        <StatCard
          title="Pending Invoices"
          :stats="`${pendingInvoicesCount} (${formatCurrency(pendingInvoicesAmount)})`"
          icon="tabler-alert-triangle"
          color="warning"
        />
      </VCol>

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

    <!-- Row 2: Revenue Trend (12 Months) -->
    <VRow class="mb-2">
      <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>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th style="width: 120px;">Month</th>
                <th style="width: 140px;" class="text-end">Revenue</th>
                <th>Trend</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in revenueByMonth" :key="row.month">
                <td class="text-body-2 font-weight-medium">
                  {{ formatMonthLabel(row.month) }}
                </td>
                <td class="text-end text-body-2 font-weight-semibold">
                  {{ formatCurrency(row.total) }}
                </td>
                <td>
                  <VProgressLinear
                    :model-value="(row.total / maxRevenue) * 100"
                    color="success"
                    height="20"
                    rounded
                    class="my-1"
                  >
                    <template #default>
                      <span class="text-caption font-weight-medium">
                        {{ Math.round((row.total / maxRevenue) * 100) }}%
                      </span>
                    </template>
                  </VProgressLinear>
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 3: Customer Growth + Churn Rate side by side -->
    <VRow class="mb-2">
      <!-- Customer Growth -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-user-plus" size="22" />
              <span>Customer Growth (12 Months)</span>
            </div>
            <VChip size="small" color="primary" variant="tonal">
              {{ totalCustomerGrowth }} total
            </VChip>
          </VCardTitle>

          <VCardText v-if="customerGrowth.length === 0" class="text-center py-8">
            <VIcon icon="tabler-users-minus" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No customer signups in the last 12 months.</div>
          </VCardText>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th style="width: 120px;">Month</th>
                <th style="width: 80px;" class="text-end">Signups</th>
                <th>Growth</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in customerGrowth" :key="row.month">
                <td class="text-body-2 font-weight-medium">
                  {{ formatMonthLabel(row.month) }}
                </td>
                <td class="text-end text-body-2 font-weight-semibold">
                  {{ row.count }}
                </td>
                <td>
                  <VProgressLinear
                    :model-value="(row.count / maxCustomerGrowth) * 100"
                    color="primary"
                    height="18"
                    rounded
                    class="my-1"
                  />
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>

      <!-- Churn Rate -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-user-minus" size="22" />
              <span>Churn Rate (6 Months)</span>
            </div>
            <VChip size="small" color="warning" variant="tonal">
              Monthly
            </VChip>
          </VCardTitle>

          <VTable density="comfortable" hover>
            <thead>
              <tr>
                <th>Month</th>
                <th class="text-end">Cancelled</th>
                <th class="text-end">Churn Rate</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in churnData" :key="row.month">
                <td class="text-body-2 font-weight-medium">
                  {{ formatMonthLabel(row.month) }}
                </td>
                <td class="text-end text-body-2">
                  {{ row.cancelled }}
                </td>
                <td class="text-end text-body-2 font-weight-semibold">
                  {{ row.rate }}%
                </td>
                <td>
                  <VChip
                    :color="resolveChurnColor(row.rate)"
                    size="small"
                    variant="tonal"
                  >
                    <VIcon
                      :icon="row.rate < 2 ? 'tabler-circle-check' : row.rate <= 5 ? 'tabler-alert-triangle' : 'tabler-alert-circle'"
                      size="14"
                      class="me-1"
                    />
                    {{ row.rate < 2 ? 'Healthy' : row.rate <= 5 ? 'Watch' : 'High' }}
                  </VChip>
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 4: Overdue Invoices -->
    <VRow class="mb-2">
      <VCol cols="12">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-alert-circle" size="22" color="error" />
              <span>Overdue Invoices</span>
            </div>
            <VChip v-if="overdueInvoices.length > 0" size="small" color="error" variant="tonal">
              {{ overdueInvoices.length }} overdue
            </VChip>
          </VCardTitle>

          <VCardText v-if="overdueInvoices.length === 0" class="text-center py-8">
            <VAvatar color="success" variant="tonal" size="56" class="mb-3">
              <VIcon icon="tabler-circle-check" size="28" />
            </VAvatar>
            <div class="text-body-1 font-weight-medium">No overdue invoices</div>
            <div class="text-body-2 text-medium-emphasis">All invoices are current.</div>
          </VCardText>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th>Customer</th>
                <th>Invoice #</th>
                <th class="text-end">Amount</th>
                <th>Due Date</th>
                <th class="text-end">Days Overdue</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="invoice in overdueInvoices" :key="invoice.id">
                <td>
                  <Link
                    v-if="invoice.user"
                    :href="`/customers/${invoice.user.id}`"
                    class="text-body-2 font-weight-medium text-primary text-decoration-none"
                  >
                    {{ invoice.user.name }}
                  </Link>
                  <span v-else class="text-body-2 text-medium-emphasis">Unknown</span>
                </td>
                <td>
                  <Link
                    :href="`/invoices/${invoice.id}`"
                    class="text-body-2 font-weight-medium text-primary text-decoration-none"
                  >
                    {{ invoice.number }}
                  </Link>
                </td>
                <td class="text-end text-body-2 font-weight-semibold text-error">
                  {{ formatCurrency(invoice.total) }}
                </td>
                <td class="text-body-2">
                  {{ formatDate(invoice.due_date) }}
                </td>
                <td class="text-end">
                  <VChip
                    :color="daysOverdue(invoice.due_date) > 30 ? 'error' : daysOverdue(invoice.due_date) > 14 ? 'warning' : 'info'"
                    size="small"
                    variant="tonal"
                  >
                    {{ daysOverdue(invoice.due_date) }} days
                  </VChip>
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 5: Recent Subscriptions & Recent Invoices -->
    <VRow class="mb-2">
      <!-- Recent Subscriptions -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-receipt" size="22" />
              <span>Recent Subscriptions</span>
            </div>
            <VChip size="small" color="primary" variant="tonal">
              Latest 10
            </VChip>
          </VCardTitle>

          <VCardText v-if="recentSubscriptions.length === 0" class="text-center py-8">
            <VIcon icon="tabler-inbox" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No subscriptions yet.</div>
          </VCardText>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th>Customer</th>
                <th>Plan</th>
                <th>Status</th>
                <th class="text-end">Price</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="sub in recentSubscriptions" :key="sub.id">
                <td>
                  <div class="d-flex flex-column">
                    <span class="text-body-2 font-weight-medium">{{ sub.user_name ?? 'Unknown' }}</span>
                    <span class="text-caption text-medium-emphasis">{{ sub.user_email ?? '' }}</span>
                  </div>
                </td>
                <td>
                  <span class="text-body-2">{{ sub.plan_name ?? sub.type }}</span>
                </td>
                <td>
                  <VChip
                    :color="resolveSubscriptionStatusColor(sub.stripe_status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ sub.stripe_status }}
                  </VChip>
                </td>
                <td class="text-end">
                  <template v-if="sub.plan_price">
                    {{ formatCurrency(sub.plan_price) }}/{{ sub.plan_billing_cycle ?? 'mo' }}
                  </template>
                  <template v-else>
                    <span class="text-medium-emphasis">&mdash;</span>
                  </template>
                </td>
                <td class="text-body-2">
                  {{ formatDate(sub.created_at) }}
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>

      <!-- Recent Invoices -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-file-invoice" size="22" />
              <span>Recent Invoices</span>
            </div>
            <VChip size="small" color="info" variant="tonal">
              Latest 10
            </VChip>
          </VCardTitle>

          <VCardText v-if="recentInvoices.length === 0" class="text-center py-8">
            <VIcon icon="tabler-inbox" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No invoices yet.</div>
          </VCardText>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th>Invoice #</th>
                <th>Customer</th>
                <th>Status</th>
                <th class="text-end">Amount</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="invoice in recentInvoices" :key="invoice.id">
                <td class="text-body-2 font-weight-medium">
                  {{ invoice.number }}
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <span class="text-body-2 font-weight-medium">{{ invoice.user?.name ?? 'Unknown' }}</span>
                    <span class="text-caption text-medium-emphasis">{{ invoice.user?.email ?? '' }}</span>
                  </div>
                </td>
                <td>
                  <VChip
                    :color="resolveInvoiceStatusColor(invoice.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ invoice.status }}
                  </VChip>
                </td>
                <td class="text-end text-body-2 font-weight-medium">
                  {{ formatCurrency(invoice.total) }}
                </td>
                <td class="text-body-2">
                  {{ formatDate(invoice.created_at) }}
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 6: Popular Plans & Revenue by Type -->
    <VRow>
      <!-- Popular Plans -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-star" size="22" />
            <span>Popular Plans</span>
          </VCardTitle>

          <VCardText v-if="popularPlans.length === 0" class="text-center py-8">
            <VIcon icon="tabler-package" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">No plans configured yet.</div>
          </VCardText>

          <VList v-else lines="two" density="comfortable">
            <VListItem
              v-for="plan in popularPlans"
              :key="plan.id"
            >
              <template #prepend>
                <VAvatar
                  :color="resolveServiceTypeColor(plan.service_type)"
                  variant="tonal"
                  rounded
                  size="40"
                >
                  <VIcon :icon="resolveServiceTypeIcon(plan.service_type)" size="22" />
                </VAvatar>
              </template>

              <VListItemTitle class="font-weight-medium">
                {{ plan.name }}
              </VListItemTitle>
              <VListItemSubtitle>
                {{ formatServiceType(plan.service_type) }} &middot; {{ formatCurrency(plan.price) }}/{{ plan.billing_cycle }}
              </VListItemSubtitle>

              <template #append>
                <div class="text-end">
                  <div class="text-body-2 font-weight-semibold">
                    {{ plan.active_services_count }}
                  </div>
                  <div class="text-caption text-medium-emphasis">
                    {{ plan.active_services_count === 1 ? 'subscriber' : 'subscribers' }}
                  </div>
                </div>
              </template>
            </VListItem>
          </VList>
        </VCard>
      </VCol>

      <!-- Revenue by Service Type -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-report-analytics" size="22" />
            <span>Revenue by Service Type</span>
          </VCardTitle>

          <VCardText v-if="revenueByServiceType.length === 0" class="text-center py-6">
            <div class="text-medium-emphasis">No revenue data available yet.</div>
          </VCardText>

          <VList v-else density="comfortable">
            <VListItem
              v-for="item in revenueByServiceType"
              :key="item.service_type"
            >
              <template #prepend>
                <VAvatar
                  :color="resolveServiceTypeColor(item.service_type)"
                  variant="tonal"
                  rounded
                  size="36"
                >
                  <VIcon :icon="resolveServiceTypeIcon(item.service_type)" size="20" />
                </VAvatar>
              </template>

              <VListItemTitle class="font-weight-medium">
                {{ formatServiceType(item.service_type) }}
              </VListItemTitle>
              <VListItemSubtitle>
                {{ item.invoice_count }} {{ item.invoice_count === 1 ? 'invoice' : 'invoices' }} paid
              </VListItemSubtitle>

              <template #append>
                <div class="text-body-2 font-weight-semibold">
                  {{ formatCurrency(item.revenue) }}
                </div>
              </template>
            </VListItem>
          </VList>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>
